如何使用Java漂亮地打印现有的JSON数据?
我有一个紧凑的JSON字符串,我想用Java很好地格式化它而不必先反序列化-例如 就像jsonlint.org一样。 有没有提供此功能的库?
类似的XML解决方案也不错。
8个解决方案
68 votes
int spacesToIndentEachLevel = 2;
new JSONObject(jsonString).toString(spacesToIndentEachLevel);
使用org.json.JSONObject(内置于JavaEE和Android中)
Heath Borders answered 2020-06-19T00:24:34Z
10 votes
一行:
String niceFormattedJson = JsonWriter.formatJson(jsonString)
要么
System.out.println(JsonWriter.formatJson(jsonString.toString()));
json-io libray([https://github.com/jdereg/json-io)]是一个小型(75K)库,除JDK外没有其他依赖项。
除了打印精美的JSON之外,您还可以将Java对象(带有循环的整个Java对象图)序列化为JSON,并读入它们。
John DeRegnaucourt answered 2020-06-19T00:25:07Z
8 votes
使用gson。 [https://www.mkyong.com/java/how-to-enable-pretty-print-json-output-gson/]
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(my_bean);
输出
{
"name": "mkyong",
"age": 35,
"position": "Founder",
"salary": 10000,
"skills": [
"java",
"python",
"shell"
]
}
susemi99 answered 2020-06-19T00:25:32Z
6 votes
如果您使用杰克逊,则可以在ObjectMapper中配置SerializationFeature轻松实现此目标:
com.fasterxml.jackson.databind.ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
mapper.writeValueAsString();
而已。
Lars Rückemann answered 2020-06-19T00:25:56Z
4 votes
我认为对于漂亮打印的东西,了解其结构非常有帮助。
要获得结构,您必须对其进行解析。 因此,我认为首先解析您拥有的JSON字符串然后再使用上面注释中提到的漂亮打印方法toString会比这容易得多。
当然,您可以对任何喜欢的JSON库执行类似的操作。
Waldheinz answered 2020-06-19T00:24:14Z
4 votes
使用gson的另一种方法:
String json_String_to_print = ...
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
return gson.toJson(jp.parse(json_String_to_print));
当您没有susemi99的帖子中的bean时,可以使用它。
vcycyv answered 2020-06-19T00:26:20Z
2 votes
我找到了一个非常简单的解决方案:
com.cedarsoftware
json-io
4.5.0
Java代码:
import com.cedarsoftware.util.io.JsonWriter;
//...
String jsonString = "json_string_plain_text";
System.out.println(JsonWriter.formatJson(jsonString));
Do Nhu Vy answered 2020-06-19T00:26:44Z
0 votes
Underscore-java库具有方法U.formatJson(json)和U.formatXml(xml)。我是项目的维护者。
Valentyn Kolesnikov answered 2020-06-19T00:27:04Z