gpt4 book ai didi

ios - 使用 Swifty JSON 解析

转载 作者:行者123 更新时间:2023-11-28 23:52:50 25 4
gpt4 key购买 nike

我的 JSON 是这样的:

{
"status": 1,
"msg": "Category Product List",
"product_data": [{
"product_id": "49",
"image": "http://192.168.1.78/Linkon/site/pub/static/frontend/Linkon/default/en_US/Magento_Catalog/images/product/placeholder/image.jpg",
"shopName": "putin",
"review": "",
"rating": "2",
"productName": "ccd",
"customrFirstName": "devi",
"customrLastName": "ss",
"address": "6th Ln, S.T.Colony, Mahalaxminagar, Rajarampuri, Kolhapur, Maharashtra 416008, India",
"contactNumber": null,
"description": "<p>ccd</p>"
},
{
"product_id": "50",
"image": "http://192.168.1.78/Linkon/site/pub/static/frontend/Linkon/default/en_US/Magento_Catalog/images/product/placeholder/image.jpg",
"shopName": "putin",
"review": "",
"rating": "2",
"productName": "car garage",
"customrFirstName": "devi",
"customrLastName": "ss",
"address": "6th Ln, S.T.Colony, Mahalaxminagar, Rajarampuri, Kolhapur, Maharashtra 416008, India",
"contactNumber": null,
"description": "<p>car garage</p>"
}
]
}

所以我的问题是:如何创建 JSON 模型类并使用 swifty JSON 进行解析?

最佳答案

我建议放弃 SwiftyJSON,转而使用 Swift 4 中内置的 CodableJSONDecoder 支持。

为此,您只需定义一个与您的 JSON 格式匹配的结构,然后对其进行解码:

struct Data: Codable {
let status: Int
let msg: String
let products: [Product]

enum CodingKeys: String, CodingKey {
case status, msg
case products = "product_data"
}
}

struct Product: Codable {
let product_id, image, shopName, review: String
let rating, productName, customrFirstName, customrLastName: String
let address: String
let contactNumber: String?
let description: String
}

do {
let data = try JSONDecoder().decode(Data.self, from: json)
print("\(data.msg)") // e.g.
} catch {
print("\(error)")
}

关于ios - 使用 Swifty JSON 解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51719298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com