【发布时间】: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,但我不推荐它,因为命名更像iOSdefinitions。
标签: ios json swift jsondecoder