【问题标题】:JSON Decode of Arrays and Dictionaries in Swift ModelSwift 模型中数组和字典的 JSON 解码
【发布时间】:2020-05-29 21:36:19
【问题描述】:

由于某种原因,我似乎无法从 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))

值得注意的是,可以有一个或多个定义。

我做错了什么?

【问题讨论】:

  • let Definition : [Definition] => let definitions : [Definition] 因为在您的 JSON 中,它是 definitions(以小写和复数开头)。如果你想保留它,你需要定义codingkeys,但我不推荐它,因为命名更像iOS definitions

标签: ios json swift jsondecoder


【解决方案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)

【讨论】:

  • 对不起我的错...@koen ..感谢您的识别:)
猜你喜欢
  • 2021-05-03
  • 2016-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-09
  • 1970-01-01
  • 2019-05-23
相关资源
最近更新 更多