[SalesForce] JSON.deserializeUntyped() not parsing the whole JSON

I am trying to parse a complex JSON String using JSON.deserializeUntyped(). It parses the first level elements correctly but the second level elements come back as type ANY, even though I am expecting it to be another Map. Following is a sample JSON String.

{
    "totalResults": 2,
    "startIndex":0,
    "pricing":[
        {
            "price":10.80,
            "cost":9.22,
            "gp":12
        },
        {
            "price":5.50,
            "cost":4.00,
            "gp":24
        }
    ]
}

My Apex code is

Map<String, Object> resultsMap = (Map<String, Object>) JSON.deserializeUntyped(jsonStr);

List<Map<String, Object>> pricing = (List<Map<String, Object>>)resultsMap.get('pricing');

I get an error on the line 2.

Invalid conversion from runtime type LIST to
LIST>

What am I doing wrong? Or what is correct way of getting the list of prices?

Best Answer

You can make the code work with an extra step:

String s = '{"totalResults": 2, "startIndex":0, "pricing":[{"price":10.80,"cost":9.22,"gp":12},{"price":5.50,"cost":4.00,"gp":24}]}';
Map<String, Object> m = (Map<String, Object>) JSON.deserializeUntyped(s);
List<Object> pricing = (List<Object>) m.get('pricing');
for (Object o : pricing) {
    Map<String, Object> p = (Map<String, Object>) o;
    System.debug('>>> ' + p);
}
Related Topic