Gson 在字符串中添加反斜杠

Gson adding backslash in String

我有一个用户定义的对象客户,它有多个属性,在其中一个属性中我们也可以有单引号、双引号和反斜杠。在将对象转换为字符串时,Gson 库会在其中添加反斜杠。 我正在使用以下代码来实现此目的,但它不起作用。

Gson gson = new GsonBuilder().disableHtmlEscaping().create();
JsonElement jsonString = gson.toJsonTree(triggerModel);

输出为

{
  "customerId": "1234",
  "customerName": "Loren",
  "customerAddress": [
    {
      "postalcode": "67676",
      "lane": "\"LA16767",
      "houseNumber": "2025",
      "society": "null"
    }
  ]
}

在 lane 属性中,原始值是 "LA16767,但它添加了一个反斜杠字符。如何以这种方式编写它,使用同一行代码处理带有单引号、双引号和反斜杠的字符串。

Gson 提供的输出是正确的,因为 "lane": ""LA16767" 不会是有效的 json。

来自json docs

A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.

您提到过:

How to write this in such a way string with single ,double quotes and backslash are handled using same line of code.

您无需执行任何特殊操作即可处理单引号、双引号和反斜杠字符。 Gson 会自动为你转义。

任何正在使用您的 json 的应用程序(服务器、UI 等)都将正确地将 "\"LA16767" 解析为 "LA16767 json ]约定。