Java 中的漂亮打印 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4105795/
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
Pretty-Print JSON in Java
提问by mabuzer
I'm using json-simpleand I need to pretty-print JSON data (make it more human readable).
我正在使用json-simple并且我需要漂亮地打印 JSON 数据(使其更具人类可读性)。
I haven't been able to find this functionality within that library. How is this commonly achieved?
我一直无法在该库中找到此功能。这通常是如何实现的?
采纳答案by Ray Hulha
回答by BuffaloBuffalo
回答by Raghu Kiran
I used org.jsonbuilt-in methods to pretty-print the data.
我使用org.json内置方法来漂亮地打印数据。
JSONObject json = new JSONObject(jsonString); // Convert text to object
System.out.println(json.toString(4)); // Print it with specified indentation
The order of fields in JSON is random per definition. A specific order is subject to parser implementation.
JSON 中字段的顺序根据定义是随机的。具体顺序取决于解析器实现。
回答by Enrique San Martín
回答by Bengt
Pretty printing with GSONin one line:
在一行中使用GSON进行漂亮的打印:
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(new JsonParser().parse(jsonString)));
Besides inlining, this is equivalent to the accepted answer.
除了内联,这相当于接受的答案。
回答by bdoughan
If you are using a Java API for JSON Processing (JSR-353) implementation then you can specify the JsonGenerator.PRETTY_PRINTING
property when you create a JsonGeneratorFactory
.
如果您使用 Java API 进行 JSON 处理 (JSR-353) 实现,那么您可以JsonGenerator.PRETTY_PRINTING
在创建JsonGeneratorFactory
.
The following example has been originally published on my blog post.
以下示例最初发布在我的博客文章中。
import java.util.*;
import javax.json.Json;
import javax.json.stream.*;
Map<String, Object> properties = new HashMap<String, Object>(1);
properties.put(JsonGenerator.PRETTY_PRINTING, true);
JsonGeneratorFactory jgf = Json.createGeneratorFactory(properties);
JsonGenerator jg = jgf.createGenerator(System.out);
jg.writeStartObject() // {
.write("name", "Jane Doe") // "name":"Jane Doe",
.writeStartObject("address") // "address":{
.write("type", 1) // "type":1,
.write("street", "1 A Street") // "street":"1 A Street",
.writeNull("city") // "city":null,
.write("verified", false) // "verified":false
.writeEnd() // },
.writeStartArray("phone-numbers") // "phone-numbers":[
.writeStartObject() // {
.write("number", "555-1111") // "number":"555-1111",
.write("extension", "123") // "extension":"123"
.writeEnd() // },
.writeStartObject() // {
.write("number", "555-2222") // "number":"555-2222",
.writeNull("extension") // "extension":null
.writeEnd() // }
.writeEnd() // ]
.writeEnd() // }
.close();
回答by Sridhar Sarnobat
Now this can be achieved with the JSONLib library:
现在这可以通过 JSONLib 库来实现:
http://json-lib.sourceforge.net/apidocs/net/sf/json/JSONObject.html
http://json-lib.sourceforge.net/apidocs/net/sf/json/JSONObject.html
If (and only if) you use the overloaded toString(int indentationFactor)
method and not the standard toString()
method.
如果(且仅当)您使用重载toString(int indentationFactor)
方法而不是标准toString()
方法。
I have verified this on the following version of the API:
我已经在以下版本的 API 上验证了这一点:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20140107</version>
</dependency>
回答by John DeRegnaucourt
In one line:
在一行中:
String niceFormattedJson = JsonWriter.formatJson(jsonString)
The json-io libray (https://github.com/jdereg/json-io) is a small (75K) library with no other dependencies than the JDK.
json-io 库 ( https://github.com/jdereg/json-io) 是一个小型 (75K) 库,除了 JDK 之外没有其他依赖项。
In addition to pretty-printing JSON, you can serialize Java objects (entire Java object graphs with cycles) to JSON, as well as read them in.
除了漂亮的打印 JSON 之外,您还可以将 Java 对象(带有循环的整个 Java 对象图)序列化为 JSON,并将它们读入。
回答by Agnes
My situation is my project uses a legacy (non-JSR) JSON parser that does not support pretty printing. However, I needed to produce pretty-printed JSON samples; this is possible without having to add any extra libraries as long as you are using Java 7 and above:
我的情况是我的项目使用不支持漂亮打印的遗留(非 JSR)JSON 解析器。但是,我需要生成打印精美的 JSON 样本;只要您使用 Java 7 及更高版本,就可以在无需添加任何额外库的情况下做到这一点:
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine scriptEngine = manager.getEngineByName("JavaScript");
scriptEngine.put("jsonString", jsonStringNoWhitespace);
scriptEngine.eval("result = JSON.stringify(JSON.parse(jsonString), null, 2)");
String prettyPrintedJson = (String) scriptEngine.get("result");
回答by Jens Piegsa
Following the JSON-P 1.0 specs (JSR-353) a more current solution for a given JsonStructure
(JsonObject
or JsonArray
) could look like this:
遵循 JSON-P 1.0 规范 ( JSR-353),针对给定JsonStructure
( JsonObject
or JsonArray
)的更当前解决方案可能如下所示:
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import javax.json.Json;
import javax.json.JsonStructure;
import javax.json.JsonWriter;
import javax.json.JsonWriterFactory;
import javax.json.stream.JsonGenerator;
public class PrettyJson {
private static JsonWriterFactory FACTORY_INSTANCE;
public static String toString(final JsonStructure status) {
final StringWriter stringWriter = new StringWriter();
final JsonWriter jsonWriter = getPrettyJsonWriterFactory()
.createWriter(stringWriter);
jsonWriter.write(status);
jsonWriter.close();
return stringWriter.toString();
}
private static JsonWriterFactory getPrettyJsonWriterFactory() {
if (null == FACTORY_INSTANCE) {
final Map<String, Object> properties = new HashMap<>(1);
properties.put(JsonGenerator.PRETTY_PRINTING, true);
FACTORY_INSTANCE = Json.createWriterFactory(properties);
}
return FACTORY_INSTANCE;
}
}