Search code examples
jsonsalesforceapex-codevisualforce

How to serialize Json string in apex


I need to parse this json string to values.

"start": { "dateTime": "2013-02-02T15:00:00+05:30" }, "end": { "dateTime": "2013-02-02T16:00:00+05:30" },

The problem is I am using JSONParser in apex (salesforce). And my class is:

 public class wrapGoogleData{

    public string summary{get;set;}
    public string id{get;set;}
    public string status;
    public creator creator;
    public start start;

    public wrapGoogleData(string entnm,string ezid,string sta, creator c,start s){
        summary= entnm;
        id= ezid;
        status = sta;
        creator = c;
        start = s;
    }  
}
public class creator{
    public string email;
    public string displayName;
    public string self;
}
public class start{
    public string datetimew;
}

I am able to get all the datat from this except the datetime in the above string. As datetime is a reserved keyword in apex so i am not able to give the variable name as datetime in my class.

Any suggestion !!

Json Parser code:

JSONParser parser = JSON.createParser(jsonData );
    while (parser.nextToken() != null) {
        // Start at the array of invoices.
        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) {
                    // Read entire invoice object, including its array of line items.
                    wrapGoogleData inv = (wrapGoogleData)parser.readValueAs(wrapGoogleData.class);

                    String s = JSON.serialize(inv);
                    system.debug('Serialized invoice: ' + s);

                    // Skip the child start array and start object markers.
                    //parser.skipChildren();
                    lstwrap.put(inv.id,inv);
                }
            }
        }
    }

Solution

  • Similar to Kumar's answer but without using an external app.

    Changing your start class was the right idea

    public class start{
        public string datetimew;
    }
    

    Now, just parse the JSON before you run it through the deserializer.

    string newjsondata = jsonData.replace('"dateTime"','"datetimew"');
    JSONParser parser = JSON.createParser(newjsondata);
    while (parser.nextToken() != null) {
       ...
    }