[英]How do I use Codable to parse this JSON?
我一直在嘗試從JSON
解析此對象,並不斷收到此錯誤:
“錯誤:typeMismatch(Swift.Array,Swift.DecodingError.Context(codingPath:[],debugDescription:“預期用於解碼Array,但找到了字典。”,underlyingError: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 \\”)。“,底層錯誤: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)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.