Sunday, February 21, 2021

How to deserializes request in Apex using deserializeUntyped(jsonString)?

deserializeUntyped(jsonString) deserializes the specified JSON string into collections of primitive data types.

Consider the below JSON for understanding the use of  deserializeUntyped(jsonString).

Let say we are receiving this JSON from external system and we want to write REST webservice to handle this request.

{

  "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 responseWrapper postrecorddatamethod(){

        RestRequest req = RestContext.request;

        RestResponse res = Restcontext.response;

        Map<String,Object> map = (Map<String,Object>) JSON.deserializeUntyped(req.requestBody.toString());

        Map<String,Object> map1= (Map<String,Object>) map.get('event');

        Map<String,Object> map2= (Map<String,Object>) map1.get('recorddata');

        String stateValue = (String) map2.get('state');

        List<Object> recordItemList= (List<Object> ) map2.get('recordItem');

        // Perform Some operations and return response

        responseWrapper obj=new responseWrapper();

        obj.message='Data Posted successfully';

        obj.statusCode = '200';

        // Overriding RestResponse object value

        res.statusCode = '200';

        return obj;

        global class responseWrapper{

        global string message;

        global integer statusCode;

        }

        

      }

   }


1 comment:

  1. thank you for the material. Content is very clear for understanding

    ReplyDelete