To Deserialize JSON you can use:
JSON.deserializeUntyped
To parse JSON for multiple levels using JSON.deserializeUntyped you need another layer of typecasting.
Here is an example:
JSON To Parse:
{
"Candidates":[
{
"Name":"ABC",
"Exp":25,
"Languages":[
{
"Name":"Apex",
"version":[
]
},
{
"Name":"Java",
"versions":[
{
"version":1.8,
"certification":true,
"placeholder":
{
"target":"reached"
}
}
]
}
]
},
{
"Name":"DEF",
"Exp":26
}
]
}
Let's say we need to reach the target attribute. Levels are Candidates>Languages>versions>placeholder>target.
You can achieve it by additional type casting for each level you move.
Here is the solution:
String jsonInput = '{'+
'"Candidates":['+
'{'+
'"Name":"ABC",'+
'"Exp":25,'+
'"Languages":['+
'{'+
'"Name":"Apex",'+
'"versions":['+
']'+
'},'+
'{' +
'"Name":"java",'+
'"versions":['+
'{'+
'"version":1.8,'+
'"certification":true,'+
'"placeholder":'+
'{'+
'"target":"reached"'+
'}'+
''+
'}'+
']'+
'}'+
']'+
'},'+
'{'+
'"Name":"DEF",'+
'"Exp":26'+
'}'+
']'+
'}';
//Deserialize the specified JSON string into collections of primitive data types.
Map<String, Object> m =
(Map<String, Object>)
JSON.deserializeUntyped(jsonInput);
//level-1
List<Object> Candidates = (List<Object>)m.get('Candidates');
for(Object Candidate : Candidates){
String Name = (String)((Map<String, Object>) Candidate).get('Name');
if(Name == 'ABC'){
//level-2
List<Object> Languages = (List<Object>)((Map<String, Object>) Candidate).get('Languages');
for(Object Language : Languages){
String LanguageName = (String)((Map<String, Object>) Language).get('Name');
if(LanguageName == 'java'){
//level-3
List<Object> versions = (List<Object>)((Map<String, Object>) Language).get('versions');
for(Object version : versions){
Decimal versionNo = (Decimal)((Map<String, Object>) version).get('version');
if(versionNo == 1.8){
//level-4
Map<String, Object> placeholder = (Map<String, Object>)((Map<String, Object>) version).get('placeholder');
//level-5
String target = (String)placeholder.get('target');
System.debug(target);
}
}
}
}
}
}