包含字典的Swift 4 Codable数组具有String和Array

时间:2018-01-01 18:08:21

标签: ios json swift parsing codable

struct ProductDetails:Codable {
    var custom_attributes:[CustomAttributesData]
    struct CustomAttributesData:Codable {
        var attribute_code:String
        var value:String
    }
}

我有Array个custom_attributes dictionary,其中elements_code的元素为String&值为String,但某些值数据类型位于Array,由于Array我无法使用codable进行解析,请帮助我,谢谢预先

"custom_attributes": [
    {
        "attribute_code": "image",
        "value": "/6/_/6.jpg"
    },
    {
        "attribute_code": "small_image",
        "value": "/6/_/6.jpg"
    }
    {
        "attribute_code": "news_to_date",
        "value": "2017-09-30 00:00:00"
    },
    {
        "attribute_code": "category_ids",
        "value": [
            "2",
            "120"
        ]
    },
    {
        "attribute_code": "options_container",
        "value": "container2"
    }
]

我在上面添加了json

1 个答案:

答案 0 :(得分:3)

您必须添加自定义初始值设定项,以区分String[String]

此代码将value声明为[String]并将单个字符串转换为数组

struct ProductDetails : Decodable {
    let custom_attributes : [CustomAttributesData]

    struct CustomAttributesData : Decodable {

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

        let attributeCode : String
        let value : [String]

        init(from decoder: Decoder) throws {
            let container = try decoder.container(keyedBy: CodingKeys.self)
            attributeCode = try container.decode(String.self, forKey: .attributeCode)
            do {
                let string = try container.decode(String.self, forKey: .value)
                value = [string]
            } catch DecodingError.typeMismatch {
                value = try container.decode([String].self, forKey: .value)
            } 
        }
    }
}

或者,您可以使用两个单独的属性stringValuearrayValue