How to deserialize a JSON response into an Apex model

Posted on October 10rd, 2014 at 1:10 pm


This post is the second part of three part series that will demonstrate how to create an HTTP request, store a JSON response into an Apex model and eventually allow us to geocode our Salesforce records. In this article, I'll demonstrate how to deserialize a JSON response and store it into a model we'll create with an Apex class.

I'll be using the Github API to get public information about my Github account. We will store information about my name, blog, location, email and avatar URL using this response:

{
  "login": "omniphx",
  "id": 3722405,
  "avatar_url": "https://avatars.githubusercontent.com/u/3722405?v=2",
  "gravatar_id": "",
  "url": "https://api.github.com/users/omniphx",
  "html_url": "https://github.com/omniphx",
  "followers_url": "https://api.github.com/users/omniphx/followers",
  "following_url": "https://api.github.com/users/omniphx/following{/other_user}",
  "gists_url": "https://api.github.com/users/omniphx/gists{/gist_id}",
  "starred_url": "https://api.github.com/users/omniphx/starred{/owner}{/repo}",
  "subscriptions_url": "https://api.github.com/users/omniphx/subscriptions",
  "organizations_url": "https://api.github.com/users/omniphx/orgs",
  "repos_url": "https://api.github.com/users/omniphx/repos",
  "events_url": "https://api.github.com/users/omniphx/events{/privacy}",
  "received_events_url": "https://api.github.com/users/omniphx/received_events",
  "type": "User",
  "site_admin": false,
  "name": "Matt Mitchener",
  "company": "",
  "blog": "http://www.mattmitchener.com/",
  "location": "Cambridge, MA",
  "email": "mattjmitchener@gmail.com",
  "hireable": false,
  "bio": null,
  "public_repos": 4,
  "public_gists": 0,
  "followers": 2,
  "following": 2,
  "created_at": "2013-02-28T01:13:31Z",
  "updated_at": "2014-10-12T12:10:27Z"
}

First step is to authorize the Github endpoint in our Salesforce org by going toSetup->Security->Remote site settings and adding a new entry with the https://api.github.com URL.

Let's start out by creating a new HTTP request and output the response with the following apex script:

String url = 'https://api.github.com/users/omniphx';

HttpRequest req = new HttpRequest();
req.setEndpoint(url);
req.setMethod('GET');

Http http = new Http();
HttpResponse res = http.send(req);
String responseBody = res.getBody();

system.debug('Github response: ' + responseBody);

If you're unfamiliar with this topic, take a look at my previous post, Creating Apex HTTP Requests.

Your output should look something like the following:

Github response: {"login":"omniphx","id":3722405,....}

This is all well and good, but we need more to work with. If we want to access properties of our response, we need to deserialize it into a model. Here's how we can create a class for our model:

public with sharing class Github {

    public class User {
        public String name;
        public String blog;
        public String location;
        public String email;
        public String avatar_url;
    }
}

The class we created will store our desired properties. It is important to remember that the deserialize() method uses our local variable names to match with the JSON property. So if we rename avatar_url to avatarUrl, that property will fail.

A common pitfall is when a JSON contains a property that matches a reserved word. For example, if we had a property called number, our call would fail we tried to compile it. You can fix this issue by using String.replace():

response = response.replace('"number":', '"user_number":');

If you're still confused by this, we'll cover an example of this happening in our next post on how to build a trigger that will geocode our Salesforce records.

Next, let's use JSON.deserialize() to store the response to our new Github class. This method requires two parameters: the response and model. Here's how it works:

String url = 'https://api.github.com/users/omniphx';

HttpRequest req = new HttpRequest();
req.setEndpoint(url);
req.setMethod('GET');

Http http = new Http();
HttpResponse res = http.send(req);
String responseBody = res.getBody();

Github github = new Github();

Github.User gUser = (Github.User)JSON.deserialize(responseBody, Github.User.class);

system.debug('Github user ' + gUser);

Output:

Github user: User:[avatar_url=https://avatars.githubusercontent.com/u/3722405?v=2, blog=http://www.mattmitchener.com/, email=mattjmitchener@gmail.com, location=Cambridge, MA, name=Matt Mitchener]

That's it! Now can easily access this information with gUser.Name or gUser.email

What's next?

Now that we know how to call HTTP requests and parse JSON responses. We will work through a real world that will use the Geocodio API to geocoding our Salesforce records.

comments powered by Disqus