Reputation: 73
I'm new to Apex and I would appreciate some help with the following:
The code below returns the entire list from input:
public static string input ='[{"item1": 1,"item2": "2","item3": [{"child1": "11","child2": "22","child3": 33}]},{"item1": "aa","item2": "bb","item3": [{"child1": "22","child2": "33","child3": 12}]}]';
List<Object> jsonParsed = (List<Object>) JSON.deserializeUntyped(input);
System.debug(jsonParsed);
and I want to get the child of "item3", so that I can read:
"item1": "1" "child1": "11" "child2": "22" "child3": 33
I have tried the code below without success, and I get item1 but null for child 1,2 and 3.
for(Object jsonParsed : jsonParsed){
Map<String,Object> ind = (Map<String,Object> )jsonParsed;
System.debug('item1 = '+ ind.get('item1'));
System.debug('child1 = '+ ind.get('item3.child1[0]'));
System.debug('child2 = '+ ind.get('item3.child2[1]'));
System.debug('child3 = '+ ind.get('item3.child3[2]'));
}
Upvotes: 0
Views: 4971
Reputation: 2759
Apex does not support relationship paths or expressions in the get()
method like this:
System.debug('child1 = '+ ind.get('item3.child1[0]'));
That will simply return null
.
You must access each level of structure in the JSON in sequence, and if you are using deserializeUntyped()
you must also cast data structures at each level (because get()
returns the generic type Object
):
Map<String, Object> item3 = (Map<String, Object>)ind.get('item3');
List<Object> child1 = (Map<String, Object>)item3.get('child1');
Object child1Item = child1[0];
System.debug('child1 = ' + child1Item);
It's generally much easier, where possible, to define a strongly-typed Apex class representing your JSON and deserialize into that. Your JSON is generic enough here that I don't see how to do that; you would need to look at the actual data types and keys and consider using a tool like JSON2Apex.
Upvotes: 1