Sunday, November 21, 2021

How to deserializes respone in Apex using deserialize(jsonString, apexType)?

 {

 {

  "nameofsystem": "ExternalSystem1",

  "event": {

    "recorddata": {

      "state": "Success",

      "recordItem": [

        {

          "id": "1",

          "name": "testRecord1"

        },

        {

          "id": "2",

          "name": "testRecord2"

        }

      ]

    }

  }

}

In webservice class,


@RestResource(urlMapping='/postrecorddata/*')

   global with sharing class postrecorddata {

       @HttpPost

      global static returnResponseWrapper postrecorddatamethod(){

        RestRequest req = RestContext.request;

        RestResponse res = Restcontext.response;

        responeWrapper wrapObj= (responeWrapper)                                            JSON.deserialize(req.requestbody.toString(),responeWrapper.class);

        // To get the the state from JSON response.

        String stateInResponse = wrapObj.event.recorddata.state;

        // Perform operations

       returnResponseWrapper obj=new returnResponseWrapper();

        obj.message='Data Posted successfully';

        obj.statusCode = '200';

        // Overriding RestResponse object value

        res.statusCode = '200';

        return obj;

        

      }

 

// Wrapper class for handling request

global class responeWrapper{

 global string nameofsystem;

 global eventData event;

 

}

global class eventData{

 global recorddataObj recorddata;

}

 

global class recorddataObj{

 global string state;

 global recordItemClass[] recordItem;

  

}

 

global class recordItemClass{

 global string id; 

 global string name;

}

// Wrapper class for handling request

 

// Wrapper class for response

      global class returnResponseWrapper{

        global string message;

        global integer statusCode;

        }

 

// Wrapper class for responde

 

}

No comments:

Post a Comment