How to Deserialize a JSON String in Apex?

Question:
How can I deserialize the following JSON string into Apex?
{
"response": {
"count": 1,
"benchmark": 0.22567009925842,
"requests": [
{
"request": {
"id": 537481,
"image_thumbnail": "",
"title": "Request for new bin(s) - residential",
"description": "Propmain ref 3234-1114",
"status": "submitted",
"address": "36 Pine Tree Close",
"location": "Peterborough, England",
"zipcode": "PE1 1EJ",
"user": "",
"date_created": 1417173208,
"count_comments": 0,
"count_followers": 0,
"count_supporters": 0,
"lat": 52.599967,
"lon": -0.233482,
"user_follows": 0,
"user_comments": 0,
"user_request": 1,
"rank": "0"
}
}
],
"status": {
"type": "success",
"message": "Success",
"code": 200,
"code_message": "Ok"
}
}
}
I’ve tried using the following code to deserialize it:
Map<String,Object> rawObj = (Map<String,Object>) JSON.deserializeUntyped(jsonString);
Map<String,Object> responseObj = (Map<String,Object>)rawObj.get('response');
List<Object> reqs = (List<Object>) responseObj.get('requests');
System.debug('Map Size = ' + reqs.size());
Map<String, Object> i = new Map<String, Object> ();
for (Object x : reqs) {
i = (Map<String, Object>)x;
}
Map<String,Object> requests = (Map<String,Object>)i.get('request');
System.debug('Map Size = ' + i.size());
for (String field : i.keySet()){
Object id = i.get(field);
Object title = i.get('title');
System.debug('Id : ' + id);
System.debug('title : ' + title);
}
The code works, but I’m looking for a more efficient and simpler way to handle this. Any suggestions?
Answer:
A more efficient and structured approach would be to generate Apex classes that match the JSON structure, which you can use for deserialization with a single JSON.deserialize
call.
Boost your career with expert Salesforce training in Chandigarh—join our free demo and start your journey to certification today!!!
Here is an example of the Apex classes generated for your JSON:
public class JSON2Apex {
public class Status {
public String type;
public String message;
public Integer code;
public String code_message;
}
public class Requests {
public Request request;
}
public class Response {
public Integer count;
public Double benchmark;
public List<Requests> requests;
public Status status;
}
public class Request {
public Integer id;
public String image_thumbnail;
public String title;
public String description;
public String status;
public String address;
public String location;
public String zipcode;
public String user;
public Integer date_created;
public Integer count_comments;
public Integer count_followers;
public Integer count_supporters;
public Double lat;
public Double lon;
public Integer user_follows;
public Integer user_comments;
public Integer user_request;
public String rank;
}
public static JSON2Apex parse(String json) {
return (JSON2Apex) System.JSON.deserialize(json, JSON2Apex.class);
}
static testMethod void testParse() {
String json = '{'+
'\"response\": {'+
' \"count\": 1,'+
' \"benchmark\": 0.22567009925842,'+
' \"requests\": ['+
' {'+
' \"request\": {'+
' \"id\": 537481,'+
' \"image_thumbnail\": \"\",'+
' \"title\": \"Request for new bin(s) - residential\",'+
' \"description\": \"Propmain ref 3234-1114\",'+
' \"status\": \"submitted\",'+
' \"address\": \"36 Pine Tree Close\",'+
' \"location\": \"Peterborough, England\",'+
' \"zipcode\": \"PE1 1EJ\",'+
' \"user\": \"\",'+
' \"date_created\": 1417173208,'+
' \"count_comments\": 0,'+
' \"count_followers\": 0,'+
' \"count_supporters\": 0,'+
' \"lat\": 52.599967,'+
' \"lon\": -0.233482,'+
' \"user_follows\": 0,'+
' \"user_comments\": 0,'+
' \"user_request\": 1,'+
' \"rank\": \"0\"'+
' }'+
' }'+
' ],'+
' \"status\": {'+
' \"type\": \"success\",'+
' \"message\": \"Success\",'+
' \"code\": 200,'+
' \"code_message\": \"Ok\"'+
' }'+
'}'+
'}';
JSON2Apex obj = parse(json);
System.assert(obj != null);
}
}
Explanation:
The code defines an Apex class JSON2Apex
with nested classes to match the structure of a given JSON response, including Status
, Requests
, Response
, and Request
classes. It includes a static method parse
to deserialize the JSON string into an instance of JSON2Apex
. A test method testParse
is provided to verify the deserialization of the sample JSON string, ensuring that the process works without errors.
You can then deserialize the JSON into an object like this:
String jsonString = 'your-json-string';
JSON2Apex obj = JSON2Apex.parse(jsonString);
System.debug(obj.response.count); // Example to access the deserialized data
Explanation:
In the above code, jsonString
contains the raw JSON data. The JSON2Apex.parse(jsonString)
method deserializes the JSON string into an instance of the JSON2Apex
class. The System.debug(obj.response.count)
line accesses and prints the count
value from the deserialized object, which is part of the response
field in the JSON.
Salesforce Training in Chandigarh – Accelerate Your Career Today!
Unlock your potential with our industry-recognized Salesforce training program in Chandigarh, tailored for aspiring professionals and seasoned experts alike. Gain in-depth knowledge of Salesforce CRM, hands-on experience with real-world projects, and expert guidance to help you ace certifications like Salesforce Admin and Developer. Our curriculum is designed to make you job-ready and elevate your career to new heights.
Our focuses on practical, industry-relevant learning. Salesforce training in Chandigarh With personalized guidance, comprehensive course materials, and expert support for certification and interview prep, we make sure you’re job-ready.
Enroll today for a free demo session and take the first step towards a successful Salesforce career!!!