Showing posts with label parse json. Show all posts
Showing posts with label parse json. 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 

Wednesday, September 11, 2013

How to parse JSON in Java

JSON slurper which parses text or reader content into a data structure of lists and maps.

Example usage:
def slurper = new JsonSlurper()
def result = slurper.parseText('{"person":{"name":"Guillaume","age":33,"pets":["dog","cat"]}}')

println "Name: "+result.person.name;
println "Age: "+result.person.age;
println "Pet Size: "+result.person.pets.size();
println "Pet[0]: "+result.person.pets[0];
println "Pet[1]: "+result.person.pets[1];

Output:
Name: Guillaume
Age: 33
Pet Size: 2
Pet[0]: dog
Pet[1]: cat
 
http://groovy.codehaus.org/gapi/groovy/json/JsonSlurper.html