Apex

Parsing JSON in Apex - Salesforce

Parsing JSON in Apex - Salesforce

Parsing JSON in Apex - Salesforce
With the growing needs of integration of Force.com platform with multiple external application it becomes crucial to know how to parse the response received which are mainly in XML or JSON format . JSON is more preferred than XML as it is light weighted and flexible.

XML parsing is explained in a different post, This post deal with the ready resources(Open Source) which can be leveraged to parse JSON .

The initial issue which a developer faces is to understand the response. The JSON which comes as a response in debug statements are not Formatted.  Use http://jsonlint.com/ to format response string. This also validates if the response is a valid JSON.

For Parsing Apex you can use http://json2apex.herokuapp.com/ .  It is a simpler tool which creates a apex class from the JSON received which can be used to parse it.

Lets take an example JSON as:

Open http://json2apex.herokuapp.com/ paste the JSON and click on Create Apex button. This will download a zip file which contains a class which can be used to parse such JSON and a test class.

Apex class created on providing the above mentioned JSON  is as below:
public class JSON2Apex {

public List<Employees> employees;

public class Employees {
public String firstName;
public String lastName;
}


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

Replicate the class in Salesforce and use the Static method JSON2Apex parse with the parameter as JSON string to get the it parsed . 

Feel free to add comments or ask questions!

About Saurabh Dua

1 comments:

  1. I had the same problem. You saved my day. Thanks so much!
    --------------------------------------------------------------------
    noi that o to dep
    phu kien do choi xe hoi
    noi that o to ha noi

    ReplyDelete

Powered by Blogger.