+ Start a Discussion
Sohan ShirodkarSohan Shirodkar 

Best way to generate JSON for requestBody

I am testing my POST REST API service in apex. 
​​​​ RestRequest request = new RestRequest();
 request.requestURI = MY_API_ENDPOINT;
 request.httpMethod = 'POST';
 request.addHeader('Content-Type', 'application/json');
 String jsonBody = '<some_json_here>';
 request.requestBody = Blob.valueOf(jsonBody);

 RestContext.request = request;

/*
 * assertions here
*/
The json string I will be using is lengthy. I can simply form a string inline in the code by use '+' operator repetatively. But what is the best way of doing this?
 
Best Answer chosen by Sohan Shirodkar
Punit@forcePunit@force
If your json text is not more than 131,072 caharacters you may use custom meta data type to store it in a field of type Text Area (Long). Custom Meta Data types are available in test methods without setting SeeAllData=true. Syntax to retrieve from custom meta data type is exactly that of SOQL. Sample query to get values from custom meta data type :
OurCustomMetadata__mdt[] rows = [SELECT Field1__c FROM OurCustomMetadata__mdt WHERE Field2__c = 'fieldValue'];
 

All Answers

Punit@forcePunit@force
If your json text is not more than 131,072 caharacters you may use custom meta data type to store it in a field of type Text Area (Long). Custom Meta Data types are available in test methods without setting SeeAllData=true. Syntax to retrieve from custom meta data type is exactly that of SOQL. Sample query to get values from custom meta data type :
OurCustomMetadata__mdt[] rows = [SELECT Field1__c FROM OurCustomMetadata__mdt WHERE Field2__c = 'fieldValue'];
 
This was selected as the best answer
Raj VakatiRaj Vakati
The best is upload your response to the static resource andr ead from the static resource .. 

 
StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
mock.setStaticResource('myStaticResourceName');
mock.setStatusCode(200);
mock.setHeader('Content-Type', 'application/json');

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_testing_static.htm
Raj VakatiRaj Vakati
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_load_data.htm

https://salesforce.stackexchange.com/questions/54527/test-loaddata-undocumented-but-useful-behavior-loading-relationships