簡體   English   中英

JSON Arrays 的解碼和 Swift ZA559B87068921EEC05086CE5485EZ 中的字典

[英]JSON Decode of Arrays and Dictionaries in Swift Model

For some reason, I can't seem to decode the following JSON from an API, probably because my model is not right for the 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"}

這是我的 model:

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

值得注意的是,可以有一個或多個定義。

我究竟做錯了什么?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM