可编码:预期对Array <any>进行解码,但找到了字典

时间:2019-04-22 14:39:48

标签: swift codable

我是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<String,String会产生:

  

typeMismatch(Swift.String,Swift.DecodingError.Context(codingPath:[CodingKeys(stringValue:“ message”,intValue:nil),_JSONKey(stringValue:“ 1dHZga0QV5ctO6yhHUhy”,intValue:nil)],debugDescription:“预期解码字符串,但找到一个字典。”,underlyingError:nil))

1 个答案:

答案 0 :(得分:2)

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)
}