【发布时间】:2018-12-29 08:29:59
【问题描述】:
我一直在尝试从我的 JSON 解析这个对象并不断收到这个错误:
“错误:类型不匹配(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: "预期解码 Array 但找到了字典。", 底层错误:nil))\n"
如果我从这里删除数组括号let video = try decoder.decode([Content].self, from: data),则会收到一条错误消息:
"错误: keyNotFound(CodingKeys(stringValue: "description", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "没有与键 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.")
}
【问题讨论】:
-
将
let video = try decoder.decode([Content].self, from: data)更改为let video = try decoder.decode(Content.self, from: data) -
当我这样做时,我收到一条错误消息:“错误:keyNotFound(CodingKeys(stringValue:“description”,intValue:nil),Swift.DecodingError.Context(codingPath:[],debugDescription: "没有与键 CodingKeys 关联的值(stringValue: \\"description\\", intValue: nil) (\\"description\\").", underlyingError: nil))\n"
标签: ios json iphone swift codable