0

I have searched internet for hours and can't find how to convert my specific JSON:

[{"_id":"55d66226726b611100aaf741","replacement":false,"quantity":5,"name":"Generator 1000 kW","maintenanceperiod":365,"lifespan":120,"cost":5000,"sku":"100003"}, {"_id":"55d66226726b611100aaf742","replacement":true,"quantity":183,"name":"Cooling Fan","maintenanceperiod":0,"lifespan":0,"cost":300,"sku":"100004"}]

Into a Map<String, Object>. Something simple like:

Map<String, Object> m = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());

Won't work as the JSON is a List when deserialized and I get the following error: 'Expecting '}' but was: '<EOF>'

1 Answer 1

2

The solution here is to deserialize into a list instead of a map because, as you noted, your JSON is a list.

// List<Object> is the list analogue to Map<String, Object> for deserializing
List<Object> untypedList = (List<Object>) JSON.deserializeUntyped(response.getBody());

// Getting at the data in a list is also similar (in that it involves explicit
//   type casting)
for(Object jsonObj :untypedList){
    // Since we're now working with a single json "object", we can
    //   re-cast it as a Map<String, Object> which will allow us to
    //   get at the juicy data contained within.
    Map<String, Object> castJsonObj = (Map<String, Object>)jsonObj;

    String externalId = (String)castJsonObj.get('_id');
    Boolean replacement = (Boolean)castJsonObj.get('replacement');
    // ...and so on
}
1
  • This answers my question. Thank you, Derek! You rock!
    – ApexNoob
    Mar 2, 2023 at 2:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .