【问题标题】:Swift 4 codable array with both object and int带有对象和 int 的 Swift 4 可编码数组
【发布时间】:2017-11-19 23:44:06
【问题描述】:

假设我有这个 JSON:

{
   "array": [
       33,
       {"id": 44, "name": "Jonas"}
   ]
}

如何编写一个 swift 4 Codable 结构来反序列化这个 JSON?

struct ArrayStruct : Codable {
    // What do I put here?
}

【问题讨论】:

  • 您的字符串不是有效的 JSON。你是说"array" :[ 吗?
  • 请注意[Any] 不符合Decodable 协议。

标签: json swift generics swift4


【解决方案1】:

您的 JSON 包含一个小错误(array 后缺少一个冒号)。您可以将数组的元素声明为具有关联值的枚举:

let jsonData = """
{
    "array": [
        33,
        {"id": 44, "name": "Jonas"}
    ]
}
""".data(using: .utf8)!

enum ArrayValue: Decodable {
    case int(Int)
    case person(Person)

    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()

        if let value = try? container.decode(Int.self) {
            self = .int(value)
        } else if let value = try? container.decode(Person.self) {
            self = .person(value)
        } else {
            let context = DecodingError.Context(codingPath: container.codingPath, debugDescription: "Unknown type")
            throw DecodingError.dataCorrupted(context)
        }
    }
}

struct Person: Decodable {
    var id: Int
    var name: String
}

struct ArrayStruct: Decodable {
    var array: [ArrayValue]
}

let temp = try JSONDecoder().decode(ArrayStruct.self, from: jsonData)
print(temp.array)

(上面的代码只显示Decodable,因为这可能是您大部分时间需要的。但Encodable 遵循类似的想法)

【讨论】:

    猜你喜欢
    • 2020-05-31
    • 1970-01-01
    • 2018-02-06
    • 2018-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-11
    相关资源
    最近更新 更多