Wednesday, October 15, 2014

JSON Parsing with Apex in Salesforce - Part I

Here, I would like to share an example of very basic JSON parsing with Apex programming language in Salesforce.

MainWrapper Class:
public class MainWrapper {
    public Integer studentId;
    public String studentName;
    public String address;
    public MainWrapper(Integer studentId, String studentName, String address) {
        this.studentId = studentId;
        this.studentName = studentName;
        this.address = address;
And now the test class to check whether JSON Parsing is working fine or not.
private class TestMainWrapper {

    static testMethod void testJsonParser() {
        String jsonMessage = '{"studentId" : 1, "studentName" : "Sudipta Deb", "address" : "Kolkata, India"}';
        JSONParser parser = JSON.createParser(jsonMessage);
        MainWrapper m = (MainWrapper)parser.readValueAs(MainWrapper.class);
        System.assertEquals(1, m.studentId);
        System.assertEquals('Sudipta Deb', m.studentName);
        System.assertEquals('Kolkata, India', m.address);

I will share more complex JSON Parsing very soon. Any feedback is always welcome.