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?
Answer
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);
}
Attribution
Source : Link , Question Author : JimKasper99 , Answer Author : Derek F