Handling JSON Payloads from Remote Endpoints in Salesforce Apex Code

This post is a part of my series on HTTP communications via Apex in Salesforce. Here are the two previous posts in the series:

In this post, we’ll look at how to handle JSON that we receive from other external endpoints. Since JSON is simply string data in a specific format, you can certainly use some string manipulation code (regular expressions, left, mid, charAt, right, etc.) to get at the data that you need but I would not recommend such an approach. Except for the most basic scenarios, that path will probably lead to pain and frustration as there is quite a lot of room for bugs. Instead, we want something that will take the JSON string data that we receive it and deserialize it into objects that we can then deal with in a type-safe manner. The built-in JSON class that Salesforce offers can help in this regard.

We’ll use the same public fake REST API from JSONPlaceholder that we used in the last episode, for today’s explorations. Let’s use the Posts GET endpoint to get some JSON data:

URL: https://jsonplaceholder.typicode.com/posts
Method: GET

This endpoint returns a JSON array that looks like this:

[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
  },
  {
    "userId": 1,
    "id": 3,
    "title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
    "body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
  }
]

We can feed this into the built-in JSON class’ deserialize method and get a List of BlogPost objects in return. That looks something like this:

public class DemoJsonDeserialization {
    public class BlogPost {
        string Title;
        string Body;
        integer UserId;
    }
    
    public static void TestRequest() {
    	HttpRequest request = new HttpRequest();
        request.setMethod('GET');            
        request.setEndpoint('https://jsonplaceholder.typicode.com/posts');
        request.setHeader('Content-Type', 'application/json; charset=UTF-8');        
                
        HttpResponse response = new HttpResponse();
        Http http = new Http();
        response = http.send(request);
        
        //System.debug(response.getBody());
        
        // If the request is successful, parse the JSON response.
        if(response.getStatusCode() == 200) {
            // Deserializes the JSON string into collections of primitive data types.
            List<BlogPost> blogPosts = (List<BlogPost>) JSON.deserialize(response.getBody(), List<BlogPost>.class);            
            
            System.debug('Received the following blogPosts:');
            for(BlogPost blog: blogPosts) {
                System.debug(blog.Title);
            }            
        }
    }
}

In my example above, you’ll see that I have a helper BlogPost class that I had hand-crafted. While that’s an option, there are free websites out there where you can feed a JSON sample and get an Apex class in return. One such resource is:

https://json2apex.herokuapp.com/

With this resource, not only do you get a JSON helper class but also an associated unit-test class.

Feeding an array of blog post entries to it yields a response such as this:

//
// Generated by JSON2Apex http://json2apex.herokuapp.com/
//

public class JSON2Apex {

	public Integer userId;
	public Integer id;
	public String title;
	public String body;

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

And the associated Unit Test class:

//
// Generated by JSON2Apex http://json2apex.herokuapp.com/
//

@IsTest
public class JSON2Apex_Test {
	
	static testMethod void testParse() {
		String json = '['+
		'  {'+
		'    \"userId\": 1,'+
		'    \"id\": 1,'+
		'    \"title\": \"sunt aut facere repellat provident occaecati excepturi optio reprehenderit\",'+
		'    \"body\": \"quia et suscipit\\nsuscipit recusandae consequuntur expedita et cum\\nreprehenderit molestiae ut ut quas totam\\nnostrum rerum est autem sunt rem eveniet architecto\"'+
		'  },'+
		'  {'+
		'    \"userId\": 1,'+
		'    \"id\": 2,'+
		'    \"title\": \"qui est esse\",'+
		'    \"body\": \"est rerum tempore vitae\\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\\nqui aperiam non debitis possimus qui neque nisi nulla\"'+
		'  },'+
		'  {'+
		'    \"userId\": 1,'+
		'    \"id\": 3,'+
		'    \"title\": \"ea molestias quasi exercitationem repellat qui ipsa sit aut\",'+
		'    \"body\": \"et iusto sed quo iure\\nvoluptatem occaecati omnis eligendi aut ad\\nvoluptatem doloribus vel accusantium quis pariatur\\nmolestiae porro eius odio et labore et velit aut\"'+
		'  }'+
		']';
		List<JSON2Apex> obj = JSON2Apex.parse(json);
		System.assert(obj != null);
	}
}

Leave a Comment

Your email address will not be published. Required fields are marked *