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
。
答案 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)
}
}
}
}
或者,您可以使用两个单独的属性stringValue
和arrayValue