+ Start a Discussion
Vishal_SharmaVishal_Sharma 

How Json responses are converted in the Following Trailhead Callout Code?

Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
request.setMethod('GET');
HttpResponse response = http.send(request);
// If the request is successful, parse the JSON response.
if (response.getStatusCode() == 200) {
    // Deserialize the JSON string into collections of primitive data types.
    Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
    // Cast the values in the 'animals' key as a list
    List<Object> animals = (List<Object>) results.get('animals');
    System.debug('Received the following animals:');
    for (Object animal: animals) {
        System.debug(animal);
    }
}

What happens after i retrieve the data using reponse.body().How is it stored.Why casting is done.

What Trialhead do i need to do ?

Raj VakatiRaj Vakati
 
This in the example in trailhead you no need to store any where ..

What happens after you retrieve the data using reponse.body(). --->, In general, we used to store or display on the front after callouts depdenets on the requirement
How is it stored. --> Generally in  objects 
Why casting is done.  --> Deserializes the specified JSON string into collections of primitive data types. like Map <String, Object> so that can you easily parse it ..  To parse the JSON it's easy if you can case it into the object rather than navigation through JSON object 
 
Http http = new Http();
HttpRequest httpRequest = new HttpRequest();
httpRequest.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
httpRequest.setMethod('GET');
HttpResponse httpResponse = http.send(httpRequest);

if (httpResponse.getStatusCode() == 200){
    Map<String,Object> responseObj = (Map<String,Object>) JSON.deserializeUntyped(httpResponse.getBody());
    
    List<Object> animalsLst = (List<Object>) responseObj.get('animals');
    
    for (Object animal:animalsLst)
        system.debug(animal);
}