我在JSON解码方面遇到问题。我为该问题添加了其他答案,并做了相同的操作,但仍然收到错误消息。我在做什么错了?
URLSession.shared.dataTask(with: r) { (data, response, error) in
do {
guard let data = data else { return }
let banners = try JSONDecoder().decode([Banner].self, from: data)
print(banners)
} catch let error as NSError {
print(error)
}
}
}.resume()
struct Banner: Decodable {
var title: String
var desc: String
var image: String
}
JSONResponse:
[
{
"id": "b4a95512-8de2-4621-8956-3289e991fb0b",
"image": "https://picsum.photos/500/324/"
},
{
"id": "4e1c703d-4841-469b-be2e-8f15d6cbd0c3",
"title": "Lays",
"image": "https://picsum.photos/500/324/"
},
{
"id": "4315705e-e6fc-4dfa-a52e-c9de2031ed53",
"desc": "ФРУТОНЯНЯ Для детского питания с яблоком, для малышей от 0 до 3 лет",
"image": "https://picsum.photos/500/324/"
},
{
"id": "0b8e40ae-5e13-4bdd-905d-a13ffdd94b65",
"title": "Бульмени",
"desc": "ГОРЯЧАЯ ШТУЧКА Со сливочным маслом",
"image": "https://picsum.photos/500/324/"
}
]
答案 0 :(得分:0)
您的结构中缺少一个"id"
键。没有为json响应中的所有元素提供desc
和title
,因此它们应该是可选的。
改为使用此结构:
struct Banner: Codable {
let id: String
let image: String
let title, desc: String?
}
此外,以这种方式捕获错误:
catch {
print(error)
}