Swift模型中数组和字典的JSON解码
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Swift模型中数组和字典的JSON解码相关的知识,希望对你有一定的参考价值。
由于某种原因,我似乎无法从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))
注意,可以有一个或多个定义。
我在做什么错?
答案
// 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)
以上是关于Swift模型中数组和字典的JSON解码的主要内容,如果未能解决你的问题,请参考以下文章
在 Swift 中解码 JSON API - 重复的结构名称