ios - 使用 Swifty JSON 解析

标签 ios swift4 swifty-json

我的 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/

相关文章:

ios - ObjectMapper 因根元素而失败

iphone - 在UIWebView中一一加载多个URL

javascript - 为什么全局 var 调试被评估为 [object Object]

ios - 使用 Swift 在 Xcode 6 中使用 xib 在自定义 uiview 中获取 SIGABRT

ios - 为什么 Swift4 会转换一个 UIButton 数组!到 [UIButton?] 类型?

ios - 如何在 SwiftyJSON 中解析数组和数组数组?

ios - 全屏显示 ViewController

ios - 在整个应用程序上设置日历类型

ios - 如何从图像路径中获取文件名

ios - Swift json 一些带引号的键有些没有