[SalesForce] Parsing Array of Nested JSON Objects

I am trying to parse an array using Apex that contains nested json data from an external REST API call. The code is shown below, the response comes back, but I want to get at the keys/fields in the json, but can't get the syntax right. The array has 3 data sets of JSON objects, but it could have more obviously.

HttpResponse response = h.send(request);
            
if (response.getStatusCode() == 200) {

  List<Object> arr =(List<Object>)JSON.deserializeUntyped(response.getBody());
    
  // this does not work, showing what I am trying
  System.debug('Data Field ----------------->' + arr[0].get('InternalID'));

}

Here is the JSON Array that comes back from my API call. I am trying to get the value of the InternalID field

[
 {
  "_id": "2e61ee4dc8501c8dc96f74d8",
  "Data": {
    "xmlns": "http://www.nasa.gov/data",
    "dataVersion": "2016v3.0",
    "DataHeader": {
      "StartDate": "2016-07-01",
      "OrgDetails": {
        "PhoneNum": 5552421111,
        "BusinessNameAlias": "NasaGov",
        "BusinessName": {
          "BusinessNameFull": "Nasa Systems"
        }
      },
      "InternalID": 222825542494
    }
  }
}
]

Best Answer

These are nested objects. As such, you have to follow each object in the path. For InternalID:

Map<String, Object> dataNode = (Map<String, Object>)arr[0].get('Data');
Map<String, Object> dataHeaderNode = (Map<String, Object>)dataNode.get('DataHeader');
String internalId = (String)dataHeaderNode.get('InternalID');

Each time you encounter a {} pair, you're in a new nested object. Also be aware that if you saw another [] in a node, it'd be a new List<Object> you have to walk through.

Related Topic