使用SwiftJson解析数组多维

时间:2019-01-17 11:48:58

标签: json swift swifty-json

我正在尝试使用以下代码和结构解析JSON:

"custom_attributes": [
    {
        "attribute_code": "api_attribute",
        "value": [
            {
                "color": [
                    {
                        "value_index": "4",
                        "label": "Red",
                        "product_super_attribute_id": "1",
                        "default_label": "Red",
                        "store_label": "Red",
                        "use_default_value": true
                    }
                ]
            },
            {
                "size": [
                    {
                        "value_index": "13",
                        "label": "35",
                        "product_super_attribute_id": "2",
                        "default_label": "35",
                        "store_label": "35",
                        "use_default_value": true
                    }
                ]
            },

我尝试过这样的代码:

Alamofire.request("http://adorableprojects.store/rest/V1/detailProduct/configurable-product").responseJSON { (responseData) -> Void in
        if((responseData.result.value) != nil) {
            let swiftyJsonVar = JSON(responseData.result.value!)
            if let resData = swiftyJsonVar["custom_attributes"]["value"]["color"].arrayObject {
                self.arrImage = resData as! [[String:AnyObject]]

但是我根本没有得到json结果。当我尝试让letData = swiftyJsonVar [“ custom_attributes”]。arrayObject时,我得到所有结果

2 个答案:

答案 0 :(得分:2)

custom_attributesvalue是数组

Alamofire.request("http://adorableprojects.store/rest/V1/detailProduct/configurable-product").responseJSON { (responseData) -> Void in
    if((responseData.result.value) != nil) {

        let swiftyJsonVar = JSON(responseData.result.value!).dictionaryValue
        if let resData = swiftyJsonVar["custom_attributes"]?.arrayValue , let sec  =  resData.first?.dictionaryValue["value"]?.arrayValue , let color =  sec.first?.dictionaryValue["color"]?.arrayValue {
             print("dhjjhdhdsjhdsjdshjdsjhds   ",color) 
        }
        else {


        }

    }
}

修改:访问大小

Alamofire.request("http://adorableprojects.store/rest/V1/detailProduct/configurable-product").responseJSON { (responseData) -> Void in
    if((responseData.result.value) != nil) {

        let swiftyJsonVar = JSON(responseData.result.value!).dictionaryValue
        if let resData = swiftyJsonVar["custom_attributes"]?.arrayValue , let sec  =  resData.first?.dictionaryValue["value"]?.arrayValue , let color =  sec[1].dictionaryValue["size"]?.arrayValue {
             print("dhjjhdhdsjhdsjdshjdsjhds   ",size) 
        }
        else {


        }

    }
}

btw推荐

struct Root: Codable {
    let customAttributes: [CustomAttribute]

    enum CodingKeys: String, CodingKey {
        case customAttributes = "custom_attributes"
    }
}

struct CustomAttribute: Codable {
    let attributeCode: String
    let value: [Value]

    enum CodingKeys: String, CodingKey {
        case attributeCode = "attribute_code"
        case value
    }
}

struct Value: Codable {
    let color: [Color]
}

struct Color: Codable {
    let valueIndex, label, productSuperAttributeID, defaultLabel: String
    let storeLabel: String
    let useDefaultValue: Bool

    enum CodingKeys: String, CodingKey {
        case valueIndex = "value_index"
        case label
        case productSuperAttributeID = "product_super_attribute_id"
        case defaultLabel = "default_label"
        case storeLabel = "store_label"
        case useDefaultValue = "use_default_value"
    }
}

答案 1 :(得分:0)

  

我建议您不要每次手动解析整个响应   可编码是用来获得Apple提供给我们的功能强大的API的。

您可以在此处了解有关可编码的更多信息:https://developer.apple.com/documentation/swift/codable

您可以定义要解析的编码键,并从Codable获取现成的模型。

编码示例:

相应地创建模型

struct Root: Codable {
    let customAttributes: [CustomAttribute]

    enum CodingKeys: String, CodingKey {
        case customAttributes = "custom_attributes"
    }
}

struct CustomAttribute: Codable {
    let attributeCode: String
    let value: [Value]

    enum CodingKeys: String, CodingKey {
        case attributeCode = "attribute_code"
        case value
    }
}

struct Value: Codable {
    let color: [Color]
}

struct Color: Codable {
    let valueIndex, label, productSuperAttributeID, defaultLabel: String
    let storeLabel: String
    let useDefaultValue: Bool

    enum CodingKeys: String, CodingKey {
        case valueIndex = "value_index"
        case label
        case productSuperAttributeID = "product_super_attribute_id"
        case defaultLabel = "default_label"
        case storeLabel = "store_label"
        case useDefaultValue = "use_default_value"
    }
}

用法:

Alamofire.request("http://adorableprojects.store/rest/V1/detailProduct/configurable-product").responseJSON { (responseData) -> Void in
                                if((responseData.result.value) != nil) {

                                    let swiftyJsonVar = JSON(responseData.result.value!)
                                    let customAttributesResponse = swiftyJsonVar["custom_attributes"]

                                    do {
                                        // You can parse response with codable's here
                                        let data = try customAttributesResponse.rawData()
                                        let customAttributes = try JSONDecoder().decode([CustomAttribute].self, from:data)
                                        print(customAttributes)
                                    }
                                    catch {
                                        debugPrint("\(#function)--\(error)")
                                    }
                                }

                            }