我一直在尝试从我的中解析这个对象JSON
并不断收到此错误:
“错误:类型不匹配(Swift.Array,
Swift.DecodingError.Context(codingPath: [], debugDescription:
“本应解码数组,但找到了字典。”,
底层错误:nil))\n"
如果我从这里删除阵列支架let video = try decoder.decode([Content].self, from: data)
然后得到一个错误说:
“错误:keyNotFound(CodingKeys(stringValue:“描述”,intValue:nil),Swift.DecodingError.Context(codingPath:[],debugDescription:“没有与键关联的值 CodingKeys(stringValue:\“描述\”,intValue:nil) ) (\"描述\").",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]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)