Search code examples
javajsongson

How to avoid backslashes in GSON JsonObject?


I have a Java POJO

public class TagBean {
  private String type;
  private String id;

  public TagBean(String type, String id) {
    this.type = type;
    this.id = id;       
  }
    // getters
    // setters   
}

I'm building pojo's and adding them to a List, as

....
List<TagBean> channelsList = new ArrayList<>();
List<TagBean> showsList = new ArrayList<>();
for each <business logic> {
   if value=channels {
      channelsList.add(new TagBean(...));
   }
   if value=shows {
      showsList.add(new TagBean(...));
   }
}

Gson gson = new GsonBuilder().create();
JsonObject tjsonObject = new JsonObject();
tjsonObject.addProperty("channels", gson.toJson(channelsList));
tjsonObject.addProperty("shows", gson.toJson(showsList));

JsonObject mainjsonObject = mainjsonObject.add("tags", tjsonObject);

return mainjsonObject;

My output is:

{
"tags": {
    "channels": "[{\"type\":\"channel\",\"id\":\"channel\",\"name\":\"Channel\",\"parent\":\"SXM\"}]",
    "shows": "[{\"type\":\"shows\",\"id\":\"shows\",\"name\":\"Shows\",\"parent\":\"SXM\"},{\"type\":\"shows\",\"id\":\"howard\",\"name\":\"Howard Stern\",\"parent\":\"shows\"},{\"type\":\"shows\",\"id\":\"howardstern\",\"name\":\"Howard Stern\",\"parent\":\"howard\"}]",
    "sports": "[]"
}
}

How can i remove the backslashes? So the output is like:

{
  "tags": {
     "channels": " [{"type":"channel","id":"channel","name":"Channel","parent":"SXM"}]",
    "shows": "[{"type":"shows","id":"shows","name":"Shows","parent":"SXM"},{"type":"shows","id":"howard","name":"Howard Stern","parent":"shows"}....

There were few other posts, but none explained this.


Solution

  • The problem is caused by this:

    tjsonObject.addProperty("channels", gson.toJson(channelsList));
    

    What that is doing is converting channelsList to a string containing a representation of the list in JSON, then setting the property to that string. Since the string contains JSON meta-characters, they must be escaped when the strings are serialized ... a second time.

    I think that you need to do this instead:

    tjsonObject.add("channels", gson.toJsonTree(channelsList));
    

    That should produce this:

    {
      "tags": {
         "channels":     
            [{"type":"channel","id":"channel","name":"Channel","parent":"SXM"}],
         "shows": 
            [{"type":"shows","id":"shows","name":"Shows","parent":"SXM"},
             {"type":"shows","id":"howard","name":"Howard Stern","parent":"shows"}
       ....
    

    That is slightly different to what your question asked for, but it has the advantage of being syntactically valid JSON!