我一直在尝试从JSON
解析这个对象,但一直收到这个错误:
"错误:类型不匹配(Swift.Array,Swift。DecodingError.Context(codingPath:[],debugDescription:"应解码数组,但找到了字典。",underlyingError:nil((\n">
如果我从这里移除数组括号let video = try decoder.decode([Content].self, from: data)
,那么会得到一个错误,说:
"错误:keyNotFound(编码键(字符串值:"description",intValue:nil(,Swift。DecodingError.Context(编码路径:[],debugDescription:"没有与键编码键关联的值(字符串值:\"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]
根对象的相应结构缺失,该结构是关键字为content
的字典({}
(。
这解释了这两个错误消息(对象是一个字典,没有关键字description
(。
键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)
}