Quantcast
Channel: Salesforce Online Training
Viewing all articles
Browse latest Browse all 84

How to Deserialize JSON into Apex Classes?

$
0
0

Question

How to Deserialize a JSON String to Apex Objects?

I need to deserialize the following JSON string into Apex objects in Salesforce:

{
    "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"
        }
    }
}

Here’s what I’ve tried so far:

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);
}

My Questions:

  1. Is there a better or more efficient way to deserialize this JSON string directly into a structured Apex class instead of working with raw maps and objects?
  2. How can I handle nested objects like request in a more streamlined manner?

Keywords: Apex, JSON, Map, Deserialize, Salesforce

Answer

There is a more efficient way to handle this using the JSON.deserialize method with a structured Apex class. Instead of manually parsing and casting the JSON string, you can define Apex classes that match the JSON structure and deserialize the JSON directly into these classes.

1: Parsing JSON Using JSON.deserializeUntyped

This snippet deserializes the JSON string into a generic Map<String, Object> using JSON.deserializeUntyped. The response key is extracted as a map, and the requests array is cast to a list. Each request is processed to extract individual attributes like title. While functional, this approach is verbose and requires repetitive typecasting.

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('Requests Size: ' + reqs.size());
Map<String, Object> i = new Map<String, Object>();
for (Object x : reqs) {
    i = (Map<String, Object>) x;
}
Map<String, Object> requestDetails = (Map<String, Object>) i.get('request');
System.debug('Title: ' + requestDetails.get('title'));

2: Defining Structured Apex Classes

This code defines structured Apex classes that align with the JSON structure. It simplifies deserialization and eliminates manual typecasting. Classes include nested objects (Response, RequestWrapper, Request, and Status) to represent the JSON hierarchy. The parse method allows you to deserialize JSON strings into an instance of the root class, JSON2Apex.

public class JSON2Apex {
    public Response response;

    public class Response {
        public Integer count;
        public Double benchmark;
        public List<RequestWrapper> requests;
        public Status status;
    }

    public class RequestWrapper {
        public Request request;
    }

    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 class Status {
        public String type;
        public String message;
        public Integer code;
        public String code_message;
    }

    public static JSON2Apex parse(String json) {
        return (JSON2Apex) JSON.deserialize(json, JSON2Apex.class);
    }
}

3: Deserializing JSON into Structured Classes

This snippet deserializes the JSON into the structured JSON2Apex class. Using the parse method, the JSON string is converted into a usable Apex object. This approach is clean and allows easy access to specific fields, such as response.count and response.requests[0].request.title. It avoids the complexity of manual typecasting and makes the code more readable.

String jsonString = '{ "response": { ... } }'; // Your JSON here
JSON2Apex parsedObj = JSON2Apex.parse(jsonString);

System.debug('Count: ' + parsedObj.response.count);
System.debug('Title of First Request: ' + parsedObj.response.requests[0].request.title);
System.debug('Status Message: ' + parsedObj.response.status.message);

Code Snippet 4: Dynamic Parsing Using JSON.deserializeUntyped

This code showcases another approach using JSON.deserializeUntyped to process JSON without predefined classes. It deserializes the JSON string into a map and extracts nested elements dynamically using casting. While useful for dynamic or unpredictable JSON, this approach can lead to harder-to-read code and potential runtime errors if the JSON structure changes.

Map<String, Object> rawObj = (Map<String, Object>) JSON.deserializeUntyped(jsonString);
Map<String, Object> responseObj = (Map<String, Object>) rawObj.get('response');
List<Object> requests = (List<Object>) responseObj.get('requests');
Map<String, Object> firstRequestWrapper = (Map<String, Object>) requests[0];
Map<String, Object> firstRequest = (Map<String, Object>) firstRequestWrapper.get('request');

System.debug('Title: ' + firstRequest.get('title'));
System.debug('Latitude: ' + firstRequest.get('lat'));

Recommendation: Using structured classes is the preferred method as it leads to clean, maintainable, and readable code. Dynamic parsing with JSON.deserializeUntyped is better suited for handling JSON with varying structures.

Summing Up

To deserialize a JSON object in Salesforce, you can use either structured Apex classes or the dynamic JSON.deserializeUntyped method.

Structured Classes Approach:

Define classes that map to the JSON structure, such as Response, Request, and Status. Use the JSON.deserialize method to convert the JSON into an Apex object. This approach is clean, avoids typecasting, and provides easy access to fields.

Dynamic Parsing Approach:

Use JSON.deserializeUntyped to parse the JSON into generic Map<String, Object> and List<Object> types. This method is flexible for handling dynamic or unpredictable JSON but requires manual typecasting and can result in less readable code.

Recommendation:

For most cases, structured classes are better due to their readability and maintainability. Dynamic parsing should be used for scenarios with variable or unknown JSON structures.

Job-Oriented Salesforce Training with 100% Money Back Assuranc

Our Salesforce Course is designed to provide you with a comprehensive understanding of the Salesforce platform, enabling you to build a rewarding career in one of the world’s most popular CRM solutions. We cover key areas such as Salesforce Admin, Developer, and AI modules, with a strong focus on hands-on learning through real-time projects. This practical approach ensures that you not only grasp theoretical concepts but also gain the skills needed to solve real-world business challenges. Led by experienced trainers, our course ensures you’re fully prepared for the dynamic demands of the Salesforce ecosystem.

In addition to technical training, our Salesforce training in Hyderabad offers personalized mentorship, expert certification guidance, and interview preparation to help you stand out in the competitive job market. You’ll receive detailed study materials, engage in live project work, and get one-on-one support to fine-tune your skills. Our goal is to ensure you’re not just ready for a certification exam, but are equipped with the practical, job-ready skills that employers value. Join us and take the first step towards mastering Salesforce and advancing your career.

The post How to Deserialize JSON into Apex Classes? appeared first on Salesforce Online Training.


Viewing all articles
Browse latest Browse all 84

Trending Articles