Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Salesforce
  3. Question
Salesforce

How can I use json.deserialize apex effectively?

Asked by Ankesh Kumar Sep 23, 2022 7.6K views 3 answers
Share

About this question

How can I deserialize this json object:


    {
    "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"
        }
    }
}
What i've tried:
 Map rawObj = (Map) JSON.deserializeUntyped(jsonString);
    Map responseObj = (Map)rawObj.get('response');
    List<Object> reqs = (List<Object>) responseObj.get('requests');
    System.debug('Map Size = ' + reqs.size());
    Map i = new Map ();
    for (Object x : reqs) {
         i = (Map)x;
}
    Map requests = (Map)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);
        //System.debug('Title : ' + title);
      }


Your answer

3 Answers

James Latest answer

Answered on Jul 29, 2024

Deserialising seems like it's going to be complicated but it can be very easy. The first step is to try to generate Apex classes for deserialisation from the JSON (this isn't always possible but usually is). I used your JSON to do this:


Once the classes are generated, deserialisation JSON to Apex is usually just a single line of code.

Was this helpful?

Ranjana Admin JanBask Expert

Answered on May 10, 2024

Using JSON.deserialize in Apex effectively involves understanding its capabilities and applying best practices for parsing JSON data. Here's a guide on how to use it effectively:


Understand the JSON Structure: Before using JSON.deserialize, make sure you understand the structure of the JSON data you're working with. This includes knowing the keys, values, and hierarchy of the JSON objects.

Define Apex Classes: To deserialize JSON into Apex objects, define corresponding Apex classes that represent the structure of the JSON data. Each class should have variables that map to the keys in the JSON objects.

Use Inner Classes for Nested Objects: If your JSON data contains nested objects, define inner classes within your main Apex class to represent these nested structures. This allows you to maintain a clear and organized structure.

Annotate Classes with @AuraEnabled (for Lightning): If you're deserializing JSON data in a Lightning component, annotate your Apex classes with @AuraEnabled to make them accessible in client-side JavaScript.

Select Appropriate Deserialization Method: Choose the appropriate JSON.deserialize method based on your requirements:

deserializeUntyped: Use this method if you're not sure about the structure of the JSON data or if it varies dynamically.

deserialize: Use this method if you know the structure of the JSON data and want to deserialize it into specific Apex classes.

Handle Errors: Implement error handling to deal with potential issues during deserialization, such as invalid JSON syntax or unexpected data types. Use try-catch blocks to catch exceptions and handle them gracefully.

Consider Performance: When deserializing large JSON payloads, consider the performance implications. Deserialization can be resource-intensive, especially for complex data structures. Optimize your code and avoid unnecessary processing.

Test Thoroughly: Test your deserialization logic with various types of JSON data, including edge cases and invalid inputs. Use unit tests to ensure that your code behaves as expected and handles different scenarios correctly.

Handle Null Values: Account for null values in the JSON data by checking for null before accessing properties or assigning values to variables. This helps prevent NullPointerExceptions.

Use System.Debug for Debugging: Use System.debug statements to debug your deserialization code and inspect the deserialized objects. This can help you identify any issues and troubleshoot them effectively.

By following these guidelines, you can use JSON.deserialize effectively in Apex to parse JSON data and work with it in your Salesforce applications.


Was this helpful?

More Salesforce discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest Salesforce Blogs

Guides, tips and career advice on Salesforce from JanBask experts.