Кодируемый: ожидается декодирование массива <Any>, но вместо него найден словарь - PullRequest
0 голосов
/ 22 апреля 2019

Я новичок в 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>

}

Выдает:

Ожидается декодирование массива, но вместо этого найден словарь.

Обновление message до Dictionary<String,String приводит к:

typeMismatch (Swift.String, Swift.DecodingError.Context (codingPath: [CodingKeys (stringValue: «message», intValue: nil), _JSONKey (stringValue: «1dHZga0QV5ctO6yhHue», nh):debugDescription: «Предполагается, что декодируется строка, но вместо этого найден словарь», underError: nil))

1 Ответ

2 голосов
/ 22 апреля 2019

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