Swift 4 Codable array with dictionary 的值为 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
    }
}

我有一个 custom_attributes 的 Arraydictionary,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"
    }
]

我在上面添加了json

您必须添加一个自定义初始化程序来区分 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