function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Raji MRaji M 

Have to read below JSON Structure

Hi All,

Can anyone help me in reading JSON Structure through Apex. I need to find the value of "D".

{
    "A" : [{
        "B" : "C",
        
    },
    {
        "B" : {
            "D" : "E"
        }
    }]
}

Thanks,
Raji M
Best Answer chosen by Raji M
Ajay K DubediAjay K Dubedi
Hi Rajeshwari,
Your JSON is not valid firstly please remove ','  after "B" : "C" from your JSON and then remove extra spaces from your JSON.
For remove extra spaces follow this link:
https://codebeautify.org/remove-extra-spaces
Try this to extract the value of D from your JSON:
string JsonStr = '{ "A" : [{ "B" : "C" }, { "B" : { "D" : "E" } }] }';
Map<String, Object> MapOne = (Map<String, Object>) JSON.deserializeUntyped(JsonStr);
List<Object> listOne = new List<Object>();
Map<String,Object> MapThree = new Map<String,Object>();
if(MapOne.containsKey('A')) {
    listOne = (List<object>) MapOne.get('A');
}
System.debug('listOne------' + listOne);
Map<String,Object> MapTwo = new Map<String,Object>();
for(object obj : listOne)
{
    MapTwo = (Map<String,Object>)obj; 
    system.debug('MapTwo----' + MapTwo);
}
system.debug('MapTwo----' + MapTwo);
if(MapTwo.containsKey('B')) {
    MapThree = (Map<String,Object>) MapTwo.get('B');
}
system.debug('MapThree----' + MapThree);
if(MapThree.containsKey('D')) {
    system.debug('Value Of D is ---- ' + MapThree.get('D'));
}

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay Dubedi

All Answers

Ajay K DubediAjay K Dubedi
Hi Rajeshwari,
Your JSON is not valid firstly please remove ','  after "B" : "C" from your JSON and then remove extra spaces from your JSON.
For remove extra spaces follow this link:
https://codebeautify.org/remove-extra-spaces
Try this to extract the value of D from your JSON:
string JsonStr = '{ "A" : [{ "B" : "C" }, { "B" : { "D" : "E" } }] }';
Map<String, Object> MapOne = (Map<String, Object>) JSON.deserializeUntyped(JsonStr);
List<Object> listOne = new List<Object>();
Map<String,Object> MapThree = new Map<String,Object>();
if(MapOne.containsKey('A')) {
    listOne = (List<object>) MapOne.get('A');
}
System.debug('listOne------' + listOne);
Map<String,Object> MapTwo = new Map<String,Object>();
for(object obj : listOne)
{
    MapTwo = (Map<String,Object>)obj; 
    system.debug('MapTwo----' + MapTwo);
}
system.debug('MapTwo----' + MapTwo);
if(MapTwo.containsKey('B')) {
    MapThree = (Map<String,Object>) MapTwo.get('B');
}
system.debug('MapThree----' + MapThree);
if(MapThree.containsKey('D')) {
    system.debug('Value Of D is ---- ' + MapThree.get('D'));
}

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay Dubedi
This was selected as the best answer