如何避免GSON JsonObject中的反斜杠?

时间:2018-07-25 04:20:39

标签: java json gson

我有一个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   
}

我正在构建pojo,并将其添加到列表中,

....
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;

我的输出是:

{
"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": "[]"
}
}

如何删除反斜杠?所以输出就像:

{
  "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"}....

其他帖子很少,但没有人对此进行解释。

3 个答案:

答案 0 :(得分:1)

问题是由以下原因引起的:

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

这是将channelsList转换为包含JSON中列表表示形式的字符串,然后将该属性设置为该字符串。由于字符串包含JSON元字符,因此必须在对字符串进行序列化时将其转义……第二次。

我认为您需要这样做:

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

应该产生这样的结果:

{
  "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"}
   ....

这与您的问题稍有不同,但是它具有语法上有效的JSON的优势!

答案 1 :(得分:0)

    String mainJsonStr = mainjsonObject.toString();
    mainJsonStr = mainJsonStr.replace("\\", "");
    System.out.println(mainJsonStr);

答案 2 :(得分:0)

问题是gson.toJson返回一个字符串,并且

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

这会将频道添加为字符串而不是JSON对象。 一种可能的解决方案是先将gson.toJson返回的字符串转换为JSON对象,然后将其添加到父JSON对象,例如

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

这会将频道视为JSON对象