【问题标题】:Gson Json conversion adding extra back slashGson Json 转换添加额外的反斜杠
【发布时间】:2022-01-10 06:19:53
【问题描述】:

我正在开发具有以下代码的服务(我可以更改此代码):

import com.google.gson.JsonObject;
import com.google.gson.Gson;

Gson gson = new Gson();
JsonObject json = new JsonObject();
json.addProperty("customer", gson.toJson(customer));
anotherServiceClient.dispatch(json.toString());

AnotherService 类代码有一个 dispatch 方法实现,它接受一个 String 对象并将其添加到一个 JSON 中,其中 party 是一个 String。我无法更改此代码。

    JsonObject json = new JsonObject();
    json.addProperty("party", inputCustomerJson);

我需要 anotherService 的输出如下:

"party": "{\"customer\":\"{\"id\":\"A123\"}"}

但它是:

"party": "{\"customer\":\"{\\\"id\\\":\\\"A123\\\"}"}

【问题讨论】:

    标签: json gson backslash


    【解决方案1】:

    问题出在这一行:

    json.addProperty("customer", gson.toJson(customer));
    

    Gson.toJson 生成一个 JSON 字符串作为输出 ("{\"id\":\"A123\"}"),因此当您稍后再次将此数据序列化为 JSON 时,反斜杠和双引号将被转义。

    您很可能想使用Gson.toJsonTreeJsonObject.add(String, JsonElement)

    json.add("customer", gson.toJsonTree(customer));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-05
      • 2021-03-15
      • 2015-06-18
      • 2021-08-24
      相关资源
      最近更新 更多