简体   繁体   English

如何使用Codable解析此JSON?

[英]How do I use Codable to parse this JSON?

I've been trying to parse this object from my JSON and keep getting this error: 我一直在尝试从JSON解析此对象,并不断收到此错误:

"Error: typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array but found a dictionary instead.", underlyingError: nil))\\n" “错误:typeMismatch(Swift.Array,Swift.DecodingError.Context(codingPath:[],debugDescription:“预期用于解码Array,但找到了字典。”,underlyingError:nil))\\ n”

If I remove Array Bracket from here let video = try decoder.decode([Content].self, from: data) then get an error saying: 如果我从此处删除阵列支架,请let video = try decoder.decode([Content].self, from: data)然后会显示一条错误消息:

"Error: keyNotFound(CodingKeys(stringValue: "description", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \\"description\\", intValue: nil) (\\"description\\").", underlyingError: nil))\\n" “错误:keyNotFound(CodingKeys(stringValue:“ description”,intValue:nil),Swift.DecodingError.Context(codingPath:[],debugDescription:“没有与键CodingKeys(stringValue:\\” description \\“,intValue:nil相关的值) )(\\“ description \\”)。“,底层错误:nil))\\ n”

How can I get this to go away? 我该如何解决? Here is my JSON and code: 这是我的JSON和代码:

    JSON: 

        > {     "content": [{
        >              "description": "Hello",
        >              "category": "World wides",
        >              "creator": {
        >              "name": "The One",
        >              "site": "Purple",
        >              "url": "http://www.sample.com"
        >              },
        >              "time": 300,
        >              "full": "https:sample2.com",
        >              "clothes": "jacket",
        >              }] 
           }


struct Content: Decodable {
    let description: String
    let category: String
}


if let fileURL = Bundle.main.url(forResource: "stub", withExtension: "json") {
    do {
        let data = try Data(contentsOf: fileURL)

        let decoder = JSONDecoder()
        let video = try decoder.decode([Content].self, from: data)

        print(video.description)

        // Success!
       // print(content.category)
    } catch {
        print("Error: \(error)")
    }
} else {
    print("No such file URL.")
}

In your JSON data, content contains an array of a single element. 在JSON数据中, content包含单个元素的数组。

I would recommend you create your structs like this: 我建议您这样创建结构:

struct Response: Decodable {
  let content: [Item]
}

struct Item: Decodable {
  let description: String
  let category: String
}

And then you can decode it and use it like this: 然后您可以对其进行解码并像这样使用它:

let response = try decoder.decode(Response.self, from: data)
guard !response.content.isEmpty else { // error handling here }
let video = response.content[0]

The corresponding struct of the root object is missing which is a dictionary ( {} ) with key content . 缺少根对象的相应结构,该结构是具有关键content的字典( {} )。

This explains both error messages (the object is a dictionary and doesn't have a key description ). 这说明了两种错误消息(该对象是一个字典,没有键description )。

The value for key content is an array so you need a loop to iterate over the items. 关键content的值是一个数组,因此您需要一个循环来迭代各项。

struct Root : Decodable {
    let content : [Content]
}

struct Content: Decodable {
    let description: String
    let category: String
}

...

let root = try decoder.decode(Root.self, from: data)
let content = root.content
for item in content {
    print(item.description)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM