如何将 JSON 对象内容编码为 JSON 字符串?

kn_*_*van 3 java json gson

试图找到一种使用 JavaScript 等转义字符对 JSON 字符串进行字符串化的方法。

例如 -

输入:

{"name":"Error","message":"hello"}
Run Code Online (Sandbox Code Playgroud)

输出:

"{\"name\":\"Error\",\"message\":\"hello\"}"
Run Code Online (Sandbox Code Playgroud)

我可以使用 Gson 将对象作为 JSON 字符串获取,但不能字符串化(使用转义字符)。

这可以用 Java 实现吗?

Sot*_*lis 5

您的输入是作为文本的 JSON 对象,大概存储在String. 您实际上是在尝试将该文本转换为 JSON 字符串。所以就这样做吧。

String input = "{\"name\":\"Error\",\"message\":\"hello\"}";
System.out.println("Original JSON content: " + input);
Gson gson = new Gson();
String jsonified = gson.toJson(input);
System.out.println("JSONified: " + jsonified);
Run Code Online (Sandbox Code Playgroud)

由于引号(和其他字符)必须在 JSON 字符串中转义,因此toJson将正确执行该转换。

上面的代码将产生

String input = "{\"name\":\"Error\",\"message\":\"hello\"}";
System.out.println("Original JSON content: " + input);
Gson gson = new Gson();
String jsonified = gson.toJson(input);
System.out.println("JSONified: " + jsonified);
Run Code Online (Sandbox Code Playgroud)

换句话说,jsonified现在包含一个 JSON 字符串的内容。

使用 Jackson,过程是相同的,只需序列化String包含 JSON 对象文本的实例

ObjectMapper mapper = new ObjectMapper();
StringWriter writer = new StringWriter();
mapper.writeValue(writer, input);
jsonified = writer.toString();
System.out.println("JSONified: " + jsonified);
Run Code Online (Sandbox Code Playgroud)

产生

Original JSON content: {"name":"Error","message":"hello"}
JSONified: "{\"name\":\"Error\",\"message\":\"hello\"}"
Run Code Online (Sandbox Code Playgroud)