deserialize(jsonString, apexType) deserializes the specified JSON string into an Apex object of the specified type.
Consider the below JSON for understanding the use of deserialize(jsonString, apexType).
Let say we are receiving this JSON from external system and we want to write REST webservice to handle this request.
{
"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 responseWrapper 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