JSON Декодирование массивов и словарей в модели Swift - PullRequest
0 голосов
/ 30 мая 2020

По какой-то причине я не могу декодировать следующий JSON из API, вероятно, потому, что моя модель не подходит для JSON:

{"definitions":[{"type":"noun","definition":"the larva of a 
butterfly.","example":null,"image_url":null,"emoji":null},
{"type":"adjective","definition":"brand of heavy equipment.","example":null,"image_url":null,"emoji":null}],
"word":"caterpillar","pronunciation":"ˈkadə(r)ˌpilər"}

Вот моя модель:

struct DefinitionReturned : Codable {
        let Definition : [Definition]
        let word : String
        let pronunciation : String

    }
    struct Definition : Codable {
        let type: String
        let definition: String
        let example: String?
        let image_url: String?
        let emoji : String?
    }

Код для декодирования:

let json = try? JSONSerialization.jsonObject(with: data, options: [])

                do {

                    let somedefinitions = try JSONDecoder().decode(DefinitionReturned.self, from: data)
                    print("here are the definitions",somedefinitions)
}

Ошибка:

ERROR IN DECODING DATA
The data couldn’t be read because it is missing.
keyNotFound(CodingKeys(stringValue: "Definition", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"Definition\", intValue: nil) (\"Definition\").", underlyingError: nil))

Следует отметить, что может быть одно или несколько определений.

Что я делаю не так?

1 Ответ

1 голос
/ 30 мая 2020
// MARK: - DefinitionReturned
struct DefinitionReturned: Codable {
    let definitions: [Definition]
    let word, pronunciation: String
}

// MARK: - Definition
struct Definition: Codable {
    let type, definition: String
    let example, imageURL, emoji: String?

    enum CodingKeys: String, CodingKey {
        case type, definition, example
        case imageURL = "image_url"
        case emoji
    }
}

Затем декодировать

let definitionReturned = try? JSONDecoder().decode(DefinitionReturned.self, from: jsonData)
...