简体   繁体   English

将带有 object 的 json 阵列添加到 Z818056DBD7E201243206B9C7CD8848 中的 Codable model

[英]add json array with object to Codable model in swift

I have json reponse from server which contains array with json object.我有来自服务器的 json 响应,其中包含带有 json object 的阵列。 How do i store it to my product modal.我如何将它存储到我的产品模式中。

{
    "status": 200,
    "image_galleries":[
        {"image_url":"8331663c9c5437a4f047ed45a56190a1-2-600x600.jpeg"},
        {"image_url":"31875021aa1f2a37f3192610223eb12b-3-600x600.jpeg"},
        {"image_url":"ac1312a66aa1bf8c34676a5d550c5e24-4-600x600.jpeg"},
        {"image_url":"5880621259e66151938a412e4197d8be-5-600x600.jpeg"}
    ],
    "id": "12345678"
}

My ProductModel我的产品型号

struct ProductModel: Codable{
    //var image_galleries: [String: [String?]]?
    var image_galleries: [String: [Array<String?>]]?
    var product_id: String?
}

Adding response object to my ProductModel将响应 object 添加到我的 ProductModel

let data = try JSONDecoder().decode(ProductModel.self, from: response!)
self.Product = data

When i print the image_galleries it always return null当我打印image_galleries它总是返回 null

print("Images", self.Product?.image_galleries as Any) // will print nil
print("Id", self.Product?.product_id) // Will print 12345678

When you are using codable you don't need to do the Array<String> and stuff like that.当您使用 codable 时,您不需要执行Array<String>之类的操作。 You can simply make an another decodable and codable and achieve it.您可以简单地制作另一个可解码和可编码并实现它。

struct ProductModel: Decodable{
    var image_galleries: [Galleries]
    let id: String
    let status: Int
}

struct Galleries: Decodable {
let image_url: String
}

Also, instead of writing image_galleries , you should use imageGalleries and when you are decoding, you can use .convertFromSnakeCase , it is a key decoding strategy as in Swift we follow camelCase instead of snake_case.另外,您应该使用imageGalleries而不是编写image_galleries ,并且在解码时可以使用.convertFromSnakeCase ,这是一个关键的解码策略,因为在Swift中我们遵循 camelCase 而不是 snake_case。

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
do {

let json = try decode.decode(ProducModel.self, from: data) 
} catch let error {
 print(error)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM