简体   繁体   English

带字典的Swift 4 Codable数组具有String和Array的值

[英]Swift 4 Codable array with dictionary has value of String and Array

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

I have an Array of custom_attributes has dictionary with elements of attribute_code as String & value as String , but some value datatype's are in Array , due to Array I am not able to parse using codable , help me out, Thanks in advance 我有一个Array custom_attributes有dictionary与attribute_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"
    }
]

I have added json above. 我在上面添加了json

You have to add a custom initializer which distinguishes between String and [String] . 您必须添加一个自定义初始值设定项,用于区分String[String]

This code declares value as [String] and converts a single string to an array 此代码将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)
            } 
        }
    }
}

Alternatively you could use two separate properties stringValue and arrayValue 或者,您可以使用两个单独的属性stringValuearrayValue

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

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