+ Start a Discussion

How To Generate JSON Request Body from Wrapper Request Class.

I am writing a REST Service and have created Request and Response Wrappers, Finding it difficult to generate the JSON Request Body out of the wrapper classes.
Below are the Sample Classes.

public class requestResource{
    public orderRequestResource order {get;set;}
public class orderRequestResource {        
    public String                                 accountUNumber             {get;set;}
    public String                                 contractNumber             {get;set;}
    public string                                 status                    {get;set;}        
    public string                                 externalKey                {get;set;}        
    public string                                 orderStartDate            {get;set;}        
    public string                                 priceBookName            {get;set;}        
    public List<orderLineItemRequestResource>     orderItems                 {get;set;}        
public class orderLineItemRequestResource{    
    public string    quantity            {get;set;}    
    public string    unitPrice           {get;set;}
    public string    description         {get;set;}
    public string    productCode         {get;set;}    
    public string    externalKey         {get;set;}
Best Answer chosen by ROHIT.KUMAR.VERMA
Naval Sharma4Naval Sharma4

If you want to populate your wrapper class properties with response data then you have to use JSON.deserialize method.
Http http = new Http();
HttpResponse res = http.send(req);
String responseBody = res.getBody();
requestResource rr = (requestResource) JSON.deserialize(responseBody, requestResource.class);

If you want to create a JSON from a class/object record then use JSON.serialize method.
// A SObject
Account acc = [SELECT Id, Name From Account Limit 1];
String JSONData = JSON.serialize(acc);

//A class
RequestResource rr = new requestResource();
String JSONData = JSON.serialize(rr);
I hope these examples will help you to understand the syntax.