I am trying to connect to an external system via REST API. The below is the JSON response.
{"coord":{"lon":-0.1257,"lat":51.5085},
"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02d"}],
"base":"stations",
"main:{"temp":292.86,"feels_like":287.94,"temp_min":292.04,"temp_max":293.71,"pressure":1027,"humidity":45},
"visibility":10000,"wind":{"speed":6.17,"deg":260},"clouds":{"all":23},"dt":1617027097,"sys":{"type":1,"id":1414,"country":"GB","sunrise":1616996538,"sunset":1617042474},"timezone":3600,"id":2643743,"name":"London","cod":200}
I am parsing it in the below manner but I would like to know if there is any standard method of parsing data. Right now, I somehow feel the below method is inefficient since the JSON string is a mix of list, array of list and objects. Could you please suggest me best practice while parsing the JSON string>
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('http://api.openweathermap.org/data/2.5/weather?q=London,uk&APPID=8ce9a754cab8e60ec7891a776bab165e');
request.setMethod('GET');
HttpResponse response = http.send(request);
system.debug(response.getBody());
system.debug(response.getStatusCode());
//Parse the JSON String into a Map
Map<String, Object> jsonParse = (Map<String, Object>)Json.deserializeUntyped(response.getbody());
system.debug('jsonMap'+jsonParse);
//Get the weather information - array of list
List<Object> listObject = (List<Object>)jsonParse.get('weather');
for(Object o: listObject){
Map<String, Object> weatherMap = (Map<String, Object>)o;
system.debug('weatherMap '+ weatherMap.get('description'));
system.debug('weatherMap '+ weatherMap.get('id'));
system.debug('weatherMap '+ weatherMap.get('main'));
system.debug('weatherMap '+ weatherMap.get('icon'));
}
String base = (String)jsonParse.get('base');
system.debug('base' + base);
Map<String,Object> main = (Map<String,Object>)jsonParse.get('main');
Decimal temperature = (Decimal)main.get('temp');
Decimal pressure = (Decimal)main.get('pressure');
Decimal humidity = (Decimal)main.get('humidity');
system.debug('temperature '+ temperature);
system.debug('pressure '+ pressure);
system.debug('humidity '+ humidity);
Map<String,Object> coord = (Map<String,Object>)jsonParse.get('coord');
Decimal latitude = (Decimal)coord.get('lat');
Decimal Longitude = (Decimal)coord.get('lon');
system.debug('latitude '+ latitude);
system.debug('longitude '+ longitude);