简体   繁体   中英

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:

"Error: typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array but found a dictionary instead.", underlyingError: nil))\\n"

If I remove Array Bracket from here let video = try decoder.decode([Content].self, from: data) then get an error saying:

"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"

How can I get this to go away? Here is my JSON and code:

    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.

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 .

This explains both error messages (the object is a dictionary and doesn't have a key description ).

The value for key content is an array so you need a loop to iterate over the items.

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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