这是我的杰森:
[ {
"id": 6854,
"name": "Laundry Iron",
"images": [
{
"id": 6856,
"src": "https://abcd.com/yzx/uploads/1750.jpg",
}
],
} ]
我们如何使模型类获得“图像”:[“ src”:“ String”]?我想抓住我尝试过的“ src”,但是它不起作用:
class ProductModel {
var title: String?
var regularPrice: Int?
var salePrice: Int?
var productDescroption: String?
var imageUrl: [ImageUrl]?
init(productJsonL: NSDictionary) {
self.title = productJsonL["name"] as? String
self.regularPrice = productJsonL["regular_price"] as? Int
self.salePrice = productJsonL["sale_price"] as? Int
self.productDescroption = productJsonL["description"] as? String
//The problem is here ........
//self.imageUrl = productJsonL["images"]![0]!["src"] as? String
self.imageUrl = ImageUrl(imageUrlJson: (productJsonL["images"]![0] as? NSDictionary)!)
}
}
class ImageUrl {
var source: String?
init(imageUrlJson: NSDictionary) {
self.source = imageUrlJson["src"] as? String
}
}
请像上面所做的那样纠正我的结构,以便我可以一次将所有内容附加到数组中?预先谢谢你!
答案 0 :(得分:1)
您需要Codable
struct Root: Codable {
let id: Int
let name: String
let images: [Image]
}
struct Image: Codable {
let id: Int
let src: String // or let src: URL
}
do {
let res = try JSONDecoder().decode([Root].self, from: data)
print(res)
}
catch {
print(error)
}