How to return Json string

2018-06-23 12:10:06

I have a Get Method which returns an invoice based on id. When I test this with Workbench I would like to have the following response:

{

"customerId": "1",

"addressId": "2018AA123",

"invoiceId": "00ec5a04a43c014aa9e8",

"invoiceType": "AdvancePayment",

"invoiceTypeLocalized": "Voorschot",

"invoiceDate": "2015-02-13T00:00:00",

"paymentDueDate": "2015-02-20T00:00:00",

"invoiceNumber": "157005888",

"startDate": "2015-03-01T00:00:00",

"endDate": "2015-04-01T00:00:00",

"periodDescription": "Maart 2015",

"amount": 100.10,

"vatAmount": 30.30,

"totalAmount": 100

}

In my workbench I end up with the following response:

"{\"attributes\":{\"type\":\"invoice__c\",

\"url\":\"/services/data/v43.0/sobjects/invoice__c/a000X000015LDn2QAA\"},

\"customerId__c\":\"1\",

\"addressId__c\":\"8212BJ154\",

\"Id\":\"a000X000015LDn2QAG\",

\"invoice ype__c\":\"AdvancePayment\",

\"invoice ypeLocalized__c\":\"Voorschot\",

\"invoiceDate__c\":\"2015-02-13\",

\"paymentDueDate__c\":\"2015-02-20\",

  • Your second response is what you get when an object is serialized to JSON twice; the first serialization produces the correct JSON and then the second serialization encodes that into a single JSON string.

    So the general solution to this sort of problem is to work out where the extra serialization is happening and eliminate that rather than trying to manipulate the extra encoding after the fact. As you have not posted any code, it is not possible to provide a more specific answer.

    PS

    This should fix the problem. The platform automatically does the serialization so you don't have to:

    @HttpGet

    global static Invoice__c getinvoiceById() {

    RestRequest request = RestContext.request;

    // grab the invoiceId from the end of the URL

    String invoiceId = request.requestURI.substring(request.requestURI.lastIndexOf('/')+1);

    List result = [SELECT customerId__c , addressId__c , Id , invoiceType__c , invoiceTypeLocalized__c , invoiceDate__c ,

    2018-06-23 14:21:33