12

I have some JSON being returned, but getting the values deeply nested is very annoying.

{  
"Result":"1",
"Matches":[  
  {  
     "BioInformation":{  
        "BirthDate":"1987-09-13T05:00:00",
        "SSN":"123456789",
        "Sex":"M"
        "UserID":"116713"
     },
     "IdInformation":{  
        "ChangeIndicator":null,
        "DataOrigin":"WebServices",
        "EntityIndicator":"P",
        "FirstName":"Test",
        "mID":"921821621",
        "LastName":"B",
        "MiddleName":null,
        "RowID":"AAAYGXBBAXAF8mZAA6",
        "SurnamePrefix":null,
        "UserID":null
     },
     "UniqueId":"AAg9eAAACAAA9eBAAA"
  },
  {  
     "BioInformation":{  
        "ConfidInd":false,
        "SSN":"123456789",
        "Sex":"N",
        "UserID":"155064"
     },
     "IdInformation":{  
        "ChangeIndicator":null,
        "DataOrigin":"WebServices",
        "EntityIndicator":"P",
        "FirstName":"Steven",
        "mID":"921821721",
        "LastName":"Johnson",
        "MiddleName":null,
        "RowID":"AADFAAKFJAA3dZDD3",
        "SurnamePrefix":null,
        "UserID":"TEST123"
     },
     "UniqueId":"AAg9eAAACAAA9eBAAB"
  }
 ]
}

I have something like:

Map<String, Object> m = (Map<String, Object>) JSON.deserializeUntyped(body); 
List<Object> matches = (List<Object>) m.get('Matches');

if (matches != null) {
    for (Object match : matches) {
        for (Object data : match) {

         }
         System.debug('match : ' + match);
    }      
}

Is there a good/easy/efficient way to access the inside information such as BirthDate, RowID, etc?

2
  • 2
    If you take your JSON over to json2apex it can build a class for you to make serialization/deserialization a snap.
    – sfdcfox
    Commented Dec 8, 2017 at 20:33
  • I also love JSON2APEX but it sometimes gets flustered by protected field names, and ends up producing the long hand version of the parsing code, even if the field in question isn't one you need. So look out for that, and consider editing the JSON first to remove any problematic field names Commented Nov 26, 2019 at 0:26

2 Answers 2

11

Use serialization/deserialization and it's quite easy. You can generate the definitions using JSON2Apex, but it's not rocket surgery and I typically prefer to do it by hand. For example you might do:

public class MyPayload
{
    public class Result
    {
        public final String uniqueId;
        public final IdInformation idInformation;
        public final BioInformation bioInformation;
    }
    public class BioInformation
    {
        final Boolean confidInd;
        final String ssn, sex, userId;
    }
    public class IdInformation
    {
        final String changeIndicator, dataOrigin, entityIndicator, mID, rowId, userId;
        final String firstName, lastName, middleName, surnamePrefix;
    }
}

Then it's easy to work with the results.

List<MyPayload.Result> results = (List<MyPayload.Result>)JSON.deserialize(
    somePayload, List<MyPayload.Result>.class
);
for (MyPayload.Result result : results)
{
    system.debug(result.idInformation.firstName);
}
0

If you don't know about the keys and values of JSON response then we need to look for other options so I added this approach to get keys and value of JSON response into map<key, value>. Reusable method to get nested objects by giving property and JSON response as a string into apex method.

Sample Data :

{
"Application": 
{ 
"email": "sa", "name": "sasa", "first_name": "sasa", "last_name": "", "phone_number": "915", "normalized_phone_number": "+9s5", 
"data": { "key1": "resumekey", "key2":"true", "key3":"false" } 
}
}

if you want to access nested data key and its value you can use this reusable approach.Please find below code.



public static Map<string,String> fetchApplicantNestedProperty(String keyToExtract,String jsonStringResponse,String parentString)
        { 
    //keyToExtract - data
   // jsonStringResponse - the json response after converting into string 
//parentString - applicant is parent key

  Map<string,String> subPropertyMap = new Map<String,String>(); 
        Map<String,Object> deserializedApplicantObjectMap =(Map<String,Object>) JSON.deserializeUntyped(jsonStringFromFountain);//jsonresponse string into map<key,object>
    System.debug('parentString'+parentString+':::'+deserializedApplicantObjectMap.get(parentString));
   
         System.debug('applicantObjectMap'+deserializedApplicantObjectMap); 
    Map<String,Object> ParsedApplicantMap=(Map<String,Object>)deserializedApplicantObjectMap.get(parentString); //applicant
    
    for(String applicantKey:ParsedApplicantMap.keySet())
     { 
    if(applicantKey==keyToExtract){ // key==data 
    System.debug('applicantkey'+applicantKey+'===>'+ParsedApplicantMap.get(applicantKey));
    
    Map<String,Object> applicantNestedPropertiesMap=(Map<String,Object>)ParsedApplicantMap.get(keyToExtract); //datakey example
    
    System.debug('applicantNestedPropertiesMap'+applicantNestedPropertiesMap); 
    
    for(String subPropertyKey:applicantNestedPropertiesMap.keySet()) //iterate data object key and value
    { //iterate data object key and its values 
    System.debug('dk'+subPropertyKey+'==>'+applicantNestedPropertiesMap.get(subPropertyKey)); 
    subPropertyMap.put(subPropertyKey,String.valueOf(applicantNestedPropertiesMap.get(subPropertyKey)));
     } 
    break; 
    } 
    } 
    return subPropertyMap; //return the nested object data as map<key,value>
    }

You must log in to answer this question.

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