Showing posts with label json deserialization. Show all posts
Showing posts with label json deserialization. Show all posts

Monday, July 25, 2016

Parse JSON in Salesforce


public class CommonJsonParser {
    public cls_Parent[] parentList;
    class cls_Parent {
        public Integer intType;
        public Double doubleType;
        public String stringType;
        public cls_Child[] childList;
    }
    class cls_Child {
        public Integer param_1;
        public String param_2;
    }
    public static CommonJsonParser parse(String json){
        return (CommonJsonParser) System.JSON.deserialize(json, CommonJsonParser.class);
    }

    public static String test() {
        String json = '{"parentList":[' + 
            '{"intType":1,"doubleType":1.5,"stringType":"String_1",' + 
            '"childList":[' + 
                '{"param_1":1,"param_2":"String_100"},' + 
                '{"param_1":5,"param_2":"String_101"}]}'+
            ',{"intType":2,"doubleType":2.5,"stringType":"String_2",' + 
            '"childList":[' + 
                '{"param_1":6,"param_2":"String_102"},' + 
                '{"param_1":2,"param_2":"String_103"},' + 
                '{"param_1":1,"param_2":"String_104"}]}]}';
        CommonJsonParser obj = parse(json);
        
        String output = '';
        
        for(cls_Parent cParent : obj.parentList) {
            output += '<br/>';
            output += '[[ Integer_Value=' + cParent.intType;
            output += ', Double_Value=' + cParent.doubleType;
            output += ', String_Value=' + cParent.stringType + ' ]]';
            
            for(cls_Child cChild: cParent.childList) {
                output += '<br/>&nbsp;&nbsp;&nbsp;&nbsp;Param_1=' + cChild.param_1;
                output += ', Param_2=' + cChild.param_2;
            }
        }
        
        return output;
    }
}
Output would be like this:

[[ Integer_Value=1, Double_Value=1.5, String_Value=String_1 ]]
    Param_1=1, Param_2=String_100
    Param_1=5, Param_2=String_101
[[ Integer_Value=2, Double_Value=2.5, String_Value=String_2 ]]
    Param_1=6, Param_2=String_102
    Param_1=2, Param_2=String_103
    Param_1=1, Param_2=String_104