Thursday, August 28, 2014

How to do JSON parsing in Apex Visualforce

Ok so today we will be looking into the Json parsing. Json is "Javascript Object Notation" a new form of format which is widle used over the http responce in webservices. It is structured and can contain data in human readable format.

To make json data salesforce provide some standard class called as System.JSON. We will be using this class to parse and then un parse the data in json.

Parsing:

  1. Create a visualforce page with controller.
  2.  Now copy this code to make a wrapper class holding name,id and phone fields
    //Subclass : Wrapper Class 
        public class Accountwrap {
            //Static Variables 
            public string id;
            public string name;
            public string Phone;
            
            //Wrapper  Class Controller
            Accountwrap(string Phone, string name, string id) {
                this.Phone = Phone;
                this.name = name;
                this.id = id;
            }
        }
  3. Now to parse this wrapper class list into a json string use this code.
    public void getlstAccount(){
            List < Accountwrap > lstwrap = new List < Accountwrap > ();
            List < account > lstacc = [SELECT Id, Name, Phone FROM Account limit 2];
            for (Account a: lstacc) {
                Accountwrap awrap = new Accountwrap(a.Phone,a.name,a.id);
                lstwrap.add(awrap);
            }
            strJson = JSON.serialize(lstwrap);
        }
  4. strJson is a public string and will get the json string,
Un-Parsing:
  1. To convert the json string we will use the same wrapper class to provide structure to the values.
  2. To un parse the string use this code
    public static List<Accountwrap> parse(String str) {
            system.debug('*****str*****'+str );
            JSONParser parser = JSON.createParser(str);
            system.debug('*****parse*****'+parser );
            List<Accountwrap> jsonstatLst = new List<Accountwrap> ();
            while (parser.nextToken() != null) { System.debug('Current token: ' +  parser.getCurrentToken() + '****JSONToken.START_ARRAY****'+JSONToken.START_ARRAY);
                if (parser.getCurrentToken() == JSONToken.START_ARRAY) {
                    while (parser.nextToken() != null) {
                        // Advance to the start object marker to
                        //  find next invoice statement object.
                        if (parser.getCurrentToken() == JSONToken.START_OBJECT) {
                            jsonstatLst.add((Accountwrap)parser.readValueAs(Accountwrap.class));
                            parser.skipChildren();
                        }
                    }
                }
            }
            return jsonstatLst;
        }
  3. jsonstatLst is a List of type wrapper class and the method can populate any list of the same type with data in wrapper object form.
Hope this helps you!!

3 comments:

  1. Hi, i am vaing trouble parsing a big array of integers that comes in a JSON response. Do you have any experience in this subject?

    This is the method that parses the response:

    public void ParsearDocumento(String js) {
    JSONParser parser = JSON.createParser(js);
    convertedChar = '';
    try{
    while (parser.nextToken() != JSONToken.END_OBJECT) {
    if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
    String text = parser.getText();
    if (parser.nextToken() != JSONToken.VALUE_NULL) {
    if (text == 'Codigo') {
    Codigo = parser.getText();
    } else if (text == 'Mensaje') {
    } else if (text == 'Base64') {
    IntBase64 = new List();
    //DoubleBase64 = new List();
    while (parser.nextToken() != JSONToken.END_ARRAY) {
    IntBase64.add(parser.getIntegerValue());
    //DoubleBase64.add(parser.getDoubleValue());
    //convertedChar += String.valueOf(parser.getDoubleValue());
    }
    } else if (text == 'Extension') {
    Extension = parser.getText();
    } else {
    System.debug(LoggingLevel.WARN, 'Root consuming unrecognized property: '+text);
    consumeObject(parser);
    }
    }
    }
    }
    }catch(JSONException ex){
    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Error al obtener documento'+ex.getMessage()));
    }
    try{
    convertedChar = String.fromCharArray(IntBase64);
    //converted = String.valueOf(EncodingUtil.base64Decode(convertedChar));
    //convertedChar = EncodingUtil.base64Encode(converted);
    }catch(StringException e){
    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Error decodificar documento'+e.getMessage()));
    }
    System.debug('Extension '+Extension);
    System.debug('Converted Char '+convertedChar);
    }

    ReplyDelete
  2. Below is another solution for deserializing instead of parsing..

    List accountsDeserialized = (List)JSON.deserialize(jsonString, List.class);

    ReplyDelete