将多个键映射到单个编码键快速

我在下面有示例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 "
    }
]

}

评论
yquo
yquo

You can define .custom(_:) for JSONDecoder.KeyDecodingStrategy

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
}
点赞
评论