-2

Okay, so I received this werid JSON format couple days back, I don't know if it is possible to decode it but I would like to learn if we could.

{
"status" : true,
"orderHistory": {
    "5" : {
        "productId" : 0,
        "productName" : "Anchovy",
        "quantity" : 1,
        "price" : "199"
        "variation": ""
    },
    
    "17" : {
        "productId" : 0,
        "productName" : "Anchovy",
        "quantity" : 1,
        "price" : "199"
        "variation": ""
    },
    
    "98" : {
        "productId" : 0,
        "productName" : "Anchovy",
        "quantity" : 1,
        "price" : "199"
        "variation": ""
    }
}

}

Order History is supposed to be an Array, but in this case backend is sending these Objects with random string keys, Reason we can't create a Decodable Model is that the keys are random,

Any ideas on how to decode this data and use it into our iOS app?

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
  • There is no need to throw the baby out with the bathwater. You can still use `JSONDecoder` here. – Sweeper Aug 27 '21 at 06:52
  • `JSONSerialization`, but you can still use `JSONDecoder` with a property at some point: `let orderHistory: [String: [OrderHistoryDecodableStruct]]` – Larme Aug 27 '21 at 07:01
  • Your JSON dataset is invalid since there's no comma after the price key. – El Tomato Aug 28 '21 at 00:08

1 Answers1

0

It is best to continue using the JSON decoder.

The root model matching the JSON would look like this:

struct Body: Decodable {
    let status: Bool
    let orderHistory: [String: Order]
}

The Order Model will be simple.

Johannes
  • 564
  • 2
  • 7