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

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

其他帖子很少,但没有人解释这一点。


不负相思意
浏览 1274回答 3
3回答

宝慕林4294392

问题是由以下原因引起的:tjsonObject.addProperty("channels", gson.toJson(channelsList));它所做的是转换channelsList为包含 JSON 列表表示的字符串,然后将该属性设置为该字符串。由于字符串包含 JSON 元字符,当字符串被序列化时它们必须被转义......第二次。我认为你需要这样做:tjsonObject.add("channels", gson.toJsonTree(channelsList));那应该产生这个:{&nbsp; "tags": {&nbsp; &nbsp; &nbsp;"channels":&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; [{"type":"channel","id":"channel","name":"Channel","parent":"SXM"}],&nbsp; &nbsp; &nbsp;"shows":&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; [{"type":"shows","id":"shows","name":"Shows","parent":"SXM"},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{"type":"shows","id":"howard","name":"Howard Stern","parent":"shows"}&nbsp; &nbsp;....这与您的问题要求的略有不同,但它的优点是语法有效 JSON!

qq_花开花谢_0

String mainJsonStr = mainjsonObject.toString();&nbsp; &nbsp; mainJsonStr = mainJsonStr.replace("\\\\", ""); //replace the \&nbsp; &nbsp; System.out.println(mainJsonStr);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java