Sunday, 4 November 2012

Native Parsing Of JSON input into User Defined Class through Apex Rest Service

I have walked into Apex Guide of SFDC to find if there are code samples for the parsing of the JSON into User defined Class in apex.Unfortunately document mentions that this can be achieved but still there were no code snippets i could find.

This blog post might help for small snippet reference to understand how we can write an apex class and structure the Constructor of the POST annotated method to achieve native parsing automatically.
Here is the Code Snippet of the Class . Note that the Request is a combination of Account and Contacts and hence we may need an inner class .

@RestResource(urlMapping='/DemoUrl/*')
global with sharing class MyRestResourcedemo{

//User defined Class

global class RequestWrapper{
Account acct;
Contact[] cons;
}

//Response Wrapper Class
  
global class ResponseWrapper{           
public String StatusCode;
public String StatusMessage;
public Account acct;
public Contact[] cons;    
}

@HttpPost
global static ResponseWrapper doPost(RequestWrapper reqst){

ResponseWrapper resp = new ResponseWrapper();
     
try{
insert reqst.acct;
for(Contact c:reqst.cons){
c.AccountId = reqst.acct.Id;
}
Upsert reqst.cons;
}
catch( Exception e ){
resp.statusCode = 'Error';
resp.statusMessage = 'Exception : ' + e.getMessage();
}
resp.statusCode = 'Done';
resp.statusMessage = 'Test success message';
resp.acct = reqst.acct;
resp.cons = reqst.cons;
return resp;
}
}
The Request Body is as shown below
{
    "reqst" :
        {
            "acct" : { 
                        "Name" : "Test Account 1",
                       "AccountNumber" : "00000001",
                       "Site" : "Site1",
                       "Website" : "www.site1.com"
                       
                     },
        
            "cons":
                [
                    { "Name": "Test Contact1", "email" : "testcontact1@test.com", "LastName":"TLName2"},
                    { "Name": "Test Contact2", "email" : "testcontact2@test.com", "LastName":"TLName3"},
                    { "Name": "Test Contact3", "email" : "testcontact3@test.com", "LastName" : "TLName"}
                ]
        }
}

The Workbench has REST Utility that simplifies testing.Attached the snapshot.







Introducing Lightning Base Components

Lightning Base Components are great addition to the platform and in fact revolutionary .One of the concerns around lightning component ...