Swift模型中数组和字典的JSON解码

问题描述 投票:0回答:1

由于某种原因,我似乎无法从API解码以下JSON,这可能是因为我的模型不适用于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))

注意,可以有一个或多个定义。

我在做什么错?

ios json swift jsondecoder
1个回答
1
投票
// 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)
© www.soinside.com 2019 - 2024. All rights reserved.