gpt4 book ai didi

ios - 我如何使用 Codable 来解析这个 JSON?

转载 作者:行者123 更新时间:2023-11-28 10:39:24 24 4
gpt4 key购买 nike

我一直在尝试从我的 JSON 中解析这个对象并不断收到这个错误:

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

如果我从这里删除 Array Bracket 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"

我怎样才能让它消失?这是我的 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.")
}

最佳答案

在您的 JSON 数据中,content 包含单个元素的数组。

我建议您像这样创建结构:

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

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

然后你可以解码它并像这样使用它:

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

关于ios - 我如何使用 Codable 来解析这个 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51452508/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com