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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44000409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 07:52:30  来源:igfitidea点击:

How can I encode JSON object content into a JSON string?

javajsongson

提问by kn_pavan

Trying to find a way to stringify a JSON string, with escape characters like JavaScript.

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

For example --

例如 -

Input:

输入:

{"name":"Error","message":"hello"}

Output:

输出:

"{\"name\":\"Error\",\"message\":\"hello\"}"

I am able to get the object as JSON String using Gson, but not stringify (with escape characters).

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

Is this possible with Java?

这可以用 Java 实现吗?

回答by Sotirios Delimanolis

Your input is a JSON object as text, presumably stored in a String. You're essentially trying to convert that textto a JSON string. So do just that.

您的输入是文本形式的 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);

Since quotes (and other characters) must be escaped in JSON strings, the toJsonwill properly perform that transformation.

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

The code above will produce the

上面的代码将产生

Original JSON content: {"name":"Error","message":"hello"}
JSONified: "{\"name\":\"Error\",\"message\":\"hello\"}"

In other words, jsonifiednow contains the content of a JSON string.

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

With Hymanson, the process is the same, just serialize the Stringinstance that contains your JSON object text

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

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

produces

产生

JSONified: "{\"name\":\"Error\",\"message\":\"hello\"}"

回答by kn_pavan

Another solution, I noted in comments:

另一个解决方案,我在评论中指出:

Hymanson's JsonStringEncoder.quoteAsString() Example: stackoverflow.com/a/40430760/639107

Hymanson 的 JsonStringEncoder.quoteAsString() 示例:stackoverflow.com/a/40430760/639107

回答by Yan.F

You can try this on your output json string :

你可以在你的输出 json 字符串上试试这个:

String strWithEscChar = output.replaceAll("\"", "\\\"");