SFDC

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:

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: