Hello friends, Today we are going to discuss How to Parse JSON Response in Apex Salesforce. Most of the JSON data we get when we do REST API Callout in Apex Class. But we face an issue that apex can’t read JSON data. So we do convert our JSON data in Apex class format. So we can read this easily.
Also check this: Get current page parameters in LWC
Highlights Points :
- We use JSON2Apex Converter.
- Tool convert the JSON data in Apex Class.
- We can use this generated class as a Wrapper class or seperated class.
Process :
Step1: First we get JSON data from REST API. Or if you already have then you can you this.
Step2: Go to JSON2Apex Converter and paste the JSON data.
Step3: Create this apex class in Org and Use for parse the data.
Code :
{
"status": "OK",
"message": "",
"zones": [
{
"countryCode": "CI",
"countryName": "C\u00f4te d'Ivoire",
"zoneName": "Africa\/Abidjan",
"gmtOffset": 0,
"timestamp": 1642527697
},
{
"countryCode": "GH",
"countryName": "Ghana",
"zoneName": "Africa\/Accra",
"gmtOffset": 0,
"timestamp": 1642527697
},
{
"countryCode": "ET",
"countryName": "Ethiopia",
"zoneName": "Africa\/Addis_Ababa",
"gmtOffset": 10800,
"timestamp": 1642538497
},
{
"countryCode": "DZ",
"countryName": "Algeria",
"zoneName": "Africa\/Algiers",
"gmtOffset": 3600,
"timestamp": 1642531297
}
]
}
JSON2Apex.cls:
//
// Generated by JSON2Apex http://json2apex.herokuapp.com/
//
public class JSON2Apex {
public String status;
public String message;
public List<Zones> zones;
public class Zones {
public String countryCode;
public String countryName;
public String zoneName;
public Integer gmtOffset;
public Integer timestamp;
}
public static JSON2Apex parse(String json) {
return (JSON2Apex) System.JSON.deserialize(json, JSON2Apex.class);
}
}
GetZoneData.cls :
public class GetZoneData {
public List<SelectOption> getItems(){
List<SelectOption> options = new List<SelectOption>();
Http ht =new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('http://api.timezonedb.com/v2/list-time-zone?key=xxxxxx&format=json');
req.setMethod('GET');
HttpResponse res = ht.send(req);
JSON2Apex obj = JSON2Apex.parse(res.getBody());
System.debug(res.getBody());
System.debug('message => ' +obj.message);
System.debug('status => ' +obj.status);
for(JSON2Apex.Zones zone : obj.zones){
options.add(new SelectOption(String.valueOf(zone.gmtOffset),zone.countryName));
}
return options;
}
}
Output :
What’s your Reaction?
+1
+1
+1
1
+1
+1
3
+1
3 comments
does not working, it throws an error “variable does not exist: obj”
HI @CAMERON , Please try this : JSON2Apex obj. I also update the code. Thanks for find bug in my code.
How to make the response fields dynamic? i.e. If I want to add a new field say “currency__c” in the Zone, then how do I do it without any change in apex code/dto?