In my last post - Integrating Salesforce with a HTTP Rest API service , I mentioned I would test out how to take the rest api's json response and convert it to an object using JSON deserialize.
If you are interested to see how to make the apex callout, please see the earlier post.
Now lets modify the earlier apex call to see how to the json string response received from the api and make an object of it. Once it is a object, we can use it to apply any of our business logic on it.
- First lets take a response of the json response we are receiving -
- As you can see we are receiving back an array of json objects. Each object as three attributes - login, firstname and lastname. Now I can create a class in Apex that matches the definition of this json object. This class will be used to convert (deserialize) the json string.
- I created an inner class "UsersFromApi" which matches the json object and added a constructor for it. Now after I make the API callout and get the result, i will use the JSON.deserialize method to convert the response string to a list of UsersFromApi class objects.
- As shown above, after checking the response code is 200, i use the JSON.deserialize method to get an output consisting of an array of UsersFromApi objects. To test this, let me write a quick anonymous code below -
thats it! now that we have an array, I can loop over it and perform any logic i need such as maybe update some fields on a Salesforce object with the values in the UsersFromApi object.
Hope this was useful for you!
Comments
Post a Comment