【问题标题】:How to make model class for dictionary inside array in swift?如何在swift中为数组内的字典制作模型类?
【发布时间】:2019-01-08 15:14:34
【问题描述】:

这是我的 Json:

[ {
    "id": 6854,
    "name": "Laundry Iron",
    "images": [
      {
        "id": 6856,
        "src": "https://abcd.com/yzx/uploads/1750.jpg",
      }
    ], 

     } ]

我们如何制作模型类来获取 "images":["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
    }

}

请像我上面所做的那样纠正我的结构,以便我可以一次将所有内容附加到数组中?提前谢谢你!

【问题讨论】:

  • ProductModel 和你的JSON 几乎没有共同点,它是从哪里来的?

标签: ios json swift api


【解决方案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)
}

【讨论】:

  • src 可以是URL(即Codable 类型)。
  • @user28434 是的,也可以是
猜你喜欢
  • 2014-12-14
  • 2017-07-16
  • 2016-09-26
  • 1970-01-01
  • 1970-01-01
  • 2016-05-15
  • 2015-08-30
  • 1970-01-01
相关资源
最近更新 更多