-1

I have the sample JSON below. There are multiple items but the keys for each item is different, but each parameter ends with same value like (ID,name,url,price,category,details).Is there any way that I can map all these items to single model.

{
"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 "
    }
]

}

manideep
  • 37
  • 8

1 Answers1

3

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
}
Adrian Bobrowski
  • 2,681
  • 1
  • 16
  • 26