【问题标题】:Codable: Expected to decode Array<Any> but found a dictionary instead可编码:预期解码 Array<Any> 但找到了字典
【发布时间】:2019-09-11 18:00:09
【问题描述】:

我是 Codable 的新手,今天一直在玩它。

我当前的 JSON 模型如下所示:

{
    "status": 200,
    "code": 200,
    "message": {
        "1dHZga0QV5ctO6yhHUhy": {
            "id": "23",
            "university_location": "Washington_DC",
            "docID": "1dHZga0QV5ctO6yhHUhy"
        },
        "0dbCMP7TrTEnpRbEleps": {
            "id": "22",
            "university_location": "Timber Trails, Nevada",
            "docID": "0dbCMP7TrTEnpRbEleps"
        }
    }
}

但是,尝试使用以下命令解码此响应:

    struct USA: Codable
{
    //String, URL, Bool and Date conform to Codable.
    var status: Int
    var code: Int

    // Message Data
    var message: Array<String>

}

给出:

本应解码 Array 但找到了字典。

message 更新为Dictionary&lt;String,String 会产生:

typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "message", intValue: nil), _JSONKey(stringValue: "1dHZga0QV5ctO6yhHUhy", intValue: nil)], debugDescription: "预期解码字符串,但找到了字典。”,基础错误:无))

【问题讨论】:

  • 我建议将您的 JSON 粘贴到 app.quicktype.io 以获得您在 Swift 中需要的结构的非常合理的第一个版本。
  • @Gereon,谢谢。那个网站真的很有用

标签: swift codable


【解决方案1】:

message 键是字典而不是数组

struct Root: Codable {
    let status, code: Int
    let message: [String: Message]
} 
struct Message: Codable {
    let id, universityLocation, docID: String

} 

do { 
    let dec = JSONDecoder()
    dec.keyDecodingStrategy = .convertFromSnakeCase
    let res = try dec.decode(Root.self, from: data) 
}
catch{
    print(error)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多