Sunday 29 June 2014

Serialize apex class to JSON salesforce

Developing an JSON output from apex class is always a challenging task for new comers. So, I have decided to post a simple apex class which generates JSON request. Below is the code snippet of class along with test class. You can extend this as per your requirement

Apex class
public class JSONserialize{
//constructor
public JSONserialize(){
Contact con = new contact();
JSONSerialize.JSONinner handler = new JSONSerialize.JSONinner();// creating instance for JSONinner class
// Set additional field
    handler.name = 'JSONinner name';
    handler.type = 'Example';
    handler.c = new JSONserialize.contact1();// creating instance for contact1 object in JSONinner class
    handler.c.firstname= 'Type a'; 
    handler.c.lastname ='Smith';
    String jsonstring = Json.serialize(handler); //this method serializes the provided inputs
    System.debug('my output :::::::::::'+jsonstring); 
    System.assert(jsonstring.contains('Type a') == true);
    }
    // belpw are two inner classes to hold the variables needed in generating JSON request
public class JSONinner{
public string name{get;set;}
public string type{get;set;}
public contact1 c{get;set;}//the line here relates JSONinner class with contact1 class.. 
 }                           //That means i can access contact1 variables from JSONinner class

public class contact1{
public string firstname{set;get;}
public string lastname{set;get;}
}
}
Test Class
@istest
private class testJSONserialize{
    static testMethod void main(){
        JSONserialize o = new JSONserialize();
    }
}
Result
{
"type" : "Example",
"name" : "JSONinner name",
  "c" : {
       "lastname" : "Smith",
       "firstname" : "Type a"
   }
}

No comments:

Post a Comment