Exploring the Different Methods of Parsing JSON in Apex

Parsing JSON data in Apex, Salesforce’s proprietary programming language is a common task for developers. JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. In this blog post, we will go over some of the different ways to parse JSON data in Apex.

⓵ Using the built-in JSON.deserialize() method The easiest and most straightforward way to parse JSON data in Apex is by using the built-in JSON.deserialize() method. This method takes a JSON string and a class type as arguments and returns an object of the specified class type. For example, let’s say we have a JSON string that represents a contact and we want to deserialize it into a Contact object.

In this example, the JSON string is deserialized into a Contact object and the debug statement will print the object’s properties.

⓶ Using the JSON.deserializeUntyped() method If the JSON string is not known at compile time, or if the JSON string contains fields that don’t match the fields in the Apex class, you can use the JSON.deserializeUntyped() method. This method returns a map of the JSON data, where the keys are the field names and the values are their corresponding values.

In this example, the JSON string is deserialized into a map of String keys and Object values.

⓷ Using the JSON.serialize() method The JSON.serialize() method can be used to convert an Apex object into a JSON string. This method takes an object as an argument and returns a JSON string representation of that object.

In this example, the Contact object is serialized into a JSON string and the debug statement will print the JSON string.

⓸ Apex JSON Parser: Apex provides a JSON.parser class which can be used to parse JSON data. This class provides methods like getCurrentValue() and nextToken() that can be used to navigate through the JSON data. This method can be useful when you need to handle complex JSON data that is not easily deserializable using the built-in Apex methods.

⓹ Using third-party libraries: There are also a number of third-party libraries available that can be used to parse JSON data in Apex. Some popular options include JSON2Apex, JSON.org, and JSON.simple. These libraries provide additional functionality and may be useful if the built-in Apex methods do not meet your needs.

JSON2Apex is a third-party library that can be used to parse JSON data in Apex. This library is useful when the built-in Apex methods do not meet your needs. It can be used to generate Apex classes that can be used to deserialize JSON strings into Apex objects. Here’s an example of how to use JSON2Apex to parse a JSON string:

First, you need to generate the Apex class using the JSON2Apex tool. You can provide a sample JSON data and the tool will generate the Apex class for you.

{
"name": "John Doe",
"age": 35,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "CA",
"zip": "12345"
},
"phoneNumbers": [
{
"type": "home",
"number": "555-555-1234"
},
{
"type": "work",
"number": "555-555-5678"
}
]
}
view raw contact.json hosted with ❤ by GitHub

Apex class will be generated like this.

public class Example {
public String name;
public Integer age;
public Address address;
public List<PhoneNumbers> phoneNumbers;
public class Address {
public String street;
public String city;
public String state;
public String zip;
}
public class PhoneNumbers {
public String type;
public String number;
}
}
view raw Example.cls hosted with ❤ by GitHub

After generating the Apex class, you can use it to deserialize the JSON string. Here is an example of how to use the generated class to deserialize the JSON string into an Apex object:

String jsonString = '{ "name": "John Doe", "age": 35, "address": { "street": "123 Main St", "city": "Anytown", "state": "CA", "zip": "12345" }, "phoneNumbers": [ { "type": "home", "number": "555-555-1234" }, { "type": "work", "number": "555-555-5678" } ] }';
Example json = (Example)JSON.deserialize(jsonString, Example.class);
System.debug(json);

In this example, the JSON string is deserialized into an Example object and the debug statement will print the object’s properties.

Please note that the name of the class might be different based on how you name it while generating the class using JSON2Apex.

JSON2Apex is a useful tool for developers who have to deal with complex JSON structures and it is a good alternative if the built-in Apex methods do not meet your needs. It allows you to easily generate Apex classes that can be used to deserialize JSON strings into Apex objects, saving you time and effort.

In conclusion, parsing JSON data in Apex is a crucial task for developers and there are multiple ways to achieve this. The built-in JSON.deserialize() method is the easiest and most straightforward way to parse JSON data, but the JSON.deserializeUntyped() method and JSON.serialize() method can also be used. Third-party libraries can also be used to provide additional functionality.

About Me

I am a certified Salesforce developer with 7 years of experience in the field. I have a passion for using my skills to help businesses make the most out of their Salesforce implementation. I specialize in Apex development, Lightning web component development, integration, and complex data manipulation using Salesforce.

Newsletter

Arun Kumar

Arun Kumar is a Certified Salesforce developer and Salesforce Champions (Platform Champions), a Computer Science graduate, working on the Salesforce platform and providing customer solutions using force.com as a Salesforce consultant/developer. He is the founder of SFDCLessons. :)

This Post Has 3 Comments

  1. Rafael

    Hi how are my friend ?
    I don’t know if it is easy for you but I am having a hard time to work with this json below and show in the lwc.

    https://developer.salesforce.com/docs/atlas.en-us.salesforce_scheduler_developer_guide.meta/salesforce_scheduler_developer_guide/uc3_get_service_territories.htm
    {
    “result” : {
    “serviceTerritories” : [{
    “city” : “San Francisco”,
    “country” : “United States”,
    “id” : “0HhRM00000002U50AI”,
    “latitude” : 37.79332,
    “longitude” : -122.392761,
    “name” : “Chase 1 Mission”,
    “operatingHoursId” : “0OHRM00000002Ps4AI”,
    “postalCode” : “94105”,
    “state” : “CA”,
    “street” : “1 Mission Street”
    }, {
    “city” : “San Francisco”,
    “country” : “United States”,
    “id” : “0HhRM00000002Tq0AI”,
    “latitude” : 37.793872,
    “longitude” : -122.394865,
    “name” : “Chase 1 Market”,
    “operatingHoursId” : “0OHRM00000002Ps4AI”,
    “postalCode” : “94105”,
    “state” : “CA”,
    “street” : “1 Market Street”
    }]
    }
    }
    If you have some tips it will be awesome

    1. Dr.Octopus

      because it’s not a JSON , JSON is between square brackets not curly ones , hope that is helpful

    2. Arun Kumar

      Hi Rafael,

      You can parse the JSON like this and display in LWC

      No data available.

      import { LightningElement } from ‘lwc’;

      const columns = [
      { label: ‘Name’, fieldName: ‘name’ },
      { label: ‘Street’, fieldName: ‘street’ },
      { label: ‘City’, fieldName: ‘city’ },
      { label: ‘State’, fieldName: ‘state’ },
      { label: ‘Postal Code’, fieldName: ‘postalCode’ },
      { label: ‘Country’, fieldName: ‘country’ }
      ];

      export default class JsonTable extends LightningElement {
      serviceTerritories = [];
      columns = columns;

      connectedCallback() {
      // Your JSON data (replace this with your actual JSON)
      const jsonString = `{
      “result”: {
      “serviceTerritories”: [
      {
      “city”: “San Francisco”,
      “country”: “United States”,
      “id”: “0HhRM00000002U50AI”,
      “latitude”: 37.79332,
      “longitude”: -122.392761,
      “name”: “Chase 1 Mission”,
      “operatingHoursId”: “0OHRM00000002Ps4AI”,
      “postalCode”: “94105”,
      “state”: “CA”,
      “street”: “1 Mission Street”
      },
      {
      “city”: “San Francisco”,
      “country”: “United States”,
      “id”: “0HhRM00000002Tq0AI”,
      “latitude”: 37.793872,
      “longitude”: -122.394865,
      “name”: “Chase 1 Market”,
      “operatingHoursId”: “0OHRM00000002Ps4AI”,
      “postalCode”: “94105”,
      “state”: “CA”,
      “street”: “1 Market Street”
      }
      ]
      }
      }`;

      // Parse the JSON data and store it in the variable
      this.serviceTerritories = JSON.parse(jsonString).result.serviceTerritories;
      }

      renderedCallback() {
      // If the data is updated, we need to notify the template to rerender
      this.template.querySelector(‘lightning-datatable’).data = this.serviceTerritories;
      }
      }

      I hope this helps!

Leave a Reply