2

I have a Map<string, String> that is populated using the following code below. When I attempt to convert this into a serialized string so that it can be passed into Blob.valueOf, the \" (backslashes) are added to the values in the map. We want to remove those values in the map.

How can I pass the serialized string so that there are no backslashes?

Code:

public class MyWrapper {
  public String firstName;
  public String lastName;
}

Map<String, String> mapToSerialize = new Map<String, String>();
list<Contact> contactList = [Select Id, FirstName, LastName from Contact];
for(Contact cont : contactList) {
  MyWrapper contWrapper = new MyWrapper();
  contWrapper.firstName = cont.FirstName;
  contWrapper.lastName = cont.LastName;

  mapToSerialize.put(cont.Id, JSON.serialize(contWrapper));
}

response.responseBody = Blob.valueOf(JSON.serialize(mapToSerialize));

Current Output:

{
  "123123" : { \"FirstName\" : \"First Name\", \"LastName\" : \"the last name\" }
}

Desired output:

{
  "123123" : { "FirstName" : "First Name", "LastName" : "the last name" }
}

What I tried, but didn't work

  1. added response.addHeader('Content-Type', 'application/json') but that returned the same output as Current Output
4

In the given scenario, serialization occurs twice in the last three lines, and it is a cause of an observed scenario.

A better way to approach this could be using of Map<String, Object> instead of Map<String, String> and perform serialization once. It would works since any entity is an Object.

For example:

Map<String, Object> mapToSerialize = new Map<String, Object>();
list<Contact> contactList = [Select Id, FirstName, LastName from Contact];
for(Contact cont : contactList) {
  MyWrapper contWrapper = new MyWrapper();
  contWrapper.firstName = cont.FirstName;
  contWrapper.lastName = cont.LastName;

  mapToSerialize.put(cont.Id, contWrapper);
}

response.responseBody = Blob.valueOf(JSON.serialize(mapToSerialize));
| improve this answer | |
  • using Map<String, Object> was the way to fix my problem. I no longer have backslashes – usernameabc Jul 10 at 16:48

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.