3

I have an Apex class similar to this:

public class MyDTO {
    public SomeComplexObject data;
    public String reportRow;
}

Where the String reportRow contains a valid JSON String.

The DTO object above is being returned as JSON from an APEX Rest service, but the reportRow contents is escaped, so the client recognises it as a String and not a complex JSON structure.

How can I prevent the escaping?

I know I could deserialize the JSON into an object, but I want this data to be generic, not bound to a specific object structure.

1

If you take responsibility for the serialization yourself, you can include Map<String, Object> fields in your DTO. (If you use the default mechanism where you return your DTO class from the method the code will not compile if the DTO class has map fields.) Such maps serialize as you would expect into JSON objects as do other maps or arrays nested within.

Here is an example:

@RestResource(urlMapping='/tmp')
global with sharing class TmpRest {

    public class MyDTO {
        public String data;
        public Map<String, Object> reportRow = new Map<String, Object>();
    }

    @HttpGet
    global static void get() {

        RestResponse res = RestContext.response;
        if (res == null) {
            res = new RestResponse();
            RestContext.response = res;
        }

        MyDTO dto = new MyDTO();
        dto.reportRow.put('abc', 123);
        dto.reportRow.put('def', new String[] {'aaa', 'bbb'});
        dto.reportRow.put('ghi', new Map<String, Object>{'xxx' => 456, 'yyy' => 'hello'});

        res.responseBody = Blob.valueOf(JSON.serialize(dto));
        res.statusCode = 200;
    }
}

that produces this JSON output:

{  
  "reportRow":{  
    "ghi":{  
      "yyy":"hello",
      "xxx":456
    },
    "def":[  
      "aaa",
      "bbb"
    ],
    "abc":123
  },
  "data":null
}

You can add whatever structure you need into the reportRow map.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.