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 Answer 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:

global with sharing class TmpRest {

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

    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:


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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .