我有一个简单的数组
big_json
但是当它包含int和string时,我如何解析JSON数组?我没有问题将内部的所有值转换为字符串,如果它们还没有,但我找不到任何函数来执行此操作。
感谢。
答案 0 :(得分:0)
将JSON示例[1, "1"]
粘贴到quicktype中,可以实现以下Codable
:
typealias IntOrStrings = [IntOrString]
enum IntOrString: Codable {
case integer(Int)
case string(String)
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let x = try? container.decode(Int.self) {
self = .integer(x)
return
}
if let x = try? container.decode(String.self) {
self = .string(x)
return
}
throw DecodingError.typeMismatch(IntOrString.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for IntOrString"))
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .integer(let x):
try container.encode(x)
case .string(let x):
try container.encode(x)
}
}
}
Here is the full source允许您执行以下操作:
let items = try IntStrings("[1, \"1\"]")
// Now you have:
// items == [.integer(1), .string("1")]
// so you can map or iterate over this
这是从JSON表示int-or-string数组的最类型安全的方法。
答案 1 :(得分:0)
您获得的Array
元素为String
或Int
,其类似于 enum
类型的数组。因此,您可以借助Type
解析基础enum
。
将基础类型结构化为:
enum StringOrIntType: Codable {
case string(String)
case int(Int)
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
do {
self = try .string(container.decode(String.self))
} catch DecodingError.typeMismatch {
do {
self = try .int(container.decode(Int.self))
} catch DecodingError.typeMismatch {
throw DecodingError.typeMismatch(StringOrIntType.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Encoded payload not of an expected type"))
}
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .int(let int):
try container.encode(int)
case .string(let string):
try container.encode(string)
}
}
}
解码过程:
let jsonData = """
["A", 1, "A1", 13, 15, 2, "B"]
""".data(using: .utf8)!
do {
let decodedArray = try JSONDecoder().decode([StringOrIntType].self, from:jsonData)
// Here, you have your Array
print(decodedArray) // [.string("A"), .int(1), .string("A1"), .int(13), .int(15), .int(2), .string("B")]
// If you want to get elements from this Array, you might do something like below
decodedArray.forEach({ (value) in
if case .string(let integer) = value {
print(integer) // "A", "A1", "B"
}
if case .int(let int) = value {
print(int) // 1, 13, 15, 2
}
})
} catch {
print(error)
}
来自对已接受答案的评论:您无需再担心商品的订购。