将多个键映射到单个编码键 swift



我在下面有示例JSON。有多个项目,但每个项目的键不同,但每个参数以相同的值结尾,例如(ID,名称,url,价格,类别,详细信息(。有什么方法可以将所有这些项目映射到单个模型。

{
"items":[
{
"ID":1000,
"name":"Bosch",
"URL":"",
"price":25000,
"categroy":"washing machines",
"details":"Bosch 6 kg Fully Automatic Front Load with In-built Heater White"
},
{
"productID":1100,
"productName":"Panasonic",
"thumnailURL":"",
"productPrice":30000,
"productCategroy":"Air Conditioners",
"productDetails":"Panasonic 1.5 Ton 3 Star Split AC with PM 2.5 Filter"
},
{
"itemID":1200,
"itemName":"Whirlpool",
"itemImageURL":"",
"itemPrice":15000,
"commodityCategroy":"Refrigerators",
"itemDetails":"Whirlpool 190 L Direct Cool Single Door 5 Star "
},
{
"commodityID":1300,
"commodityName":"Samsung",
"commodityImageURL":"",
"commodityPrice":13000,
"itemCategroy":"TVs",
"commodityDetails":"Samsung Series 4 80cm (32 inch) HD Ready LED Smart TV "
}
]

}

您可以为JSONDecoder.KeyDecodingStrategy定义.custom(_:)

enum YourCodingKey: String, CodingKey, CaseIterable {
case id = "ID"
case name = "name"
case url = "URL"
case price = "price"
case category = "category"
case details = "details"
}
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .custom { keys in
YourCodingKey.allCases
.first { keys.last.unsafelyUnwrapped.stringValue.hasSuffix($0.stringValue)}
.unsafelyUnwrapped
}

相关内容

  • 没有找到相关文章

最新更新