我使用JSON -simple,我需要漂亮地打印JSON数据(使其更易于阅读)。
我还没能在那个库中找到这个功能。 这通常是如何实现的?
我使用JSON -simple,我需要漂亮地打印JSON数据(使其更易于阅读)。
我还没能在那个库中找到这个功能。 这通常是如何实现的?
当前回答
漂亮的打印与GSON一行:
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(new JsonParser().parse(jsonString)));
除了内联之外,这等价于已接受的答案。
其他回答
与杰克逊(com.fasterxml.jackson.databind):
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject))
如何启用漂亮的JSON打印输出(Jackson)
我知道这已经在答案中,但我想在这里单独写它,因为很可能您已经将Jackson作为依赖项,因此您需要的只是额外的一行代码
现在这可以通过JSONLib库实现:
http://json-lib.sourceforge.net/apidocs/net/sf/json/JSONObject.html
当(且仅当)你使用重载的toString(int indentationFactor)方法而不是标准的toString()方法。
我已经在以下版本的API上验证了这一点:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20140107</version>
</dependency>
你可以使用小的json库
String jsonstring = ....;
JsonValue json = JsonParser.parse(jsonstring);
String jsonIndendedByTwoSpaces = json.toPrettyString(" ");
这招对我很管用,用了杰克逊的话:
mapper.writerWithDefaultPrettyPrinter().writeValueAsString(JSONString)
我用的是org。Json内置方法来漂亮地打印数据。
import org.json.JSONObject;
JSONObject json = new JSONObject(jsonString); // Convert text to object
System.out.println(json.toString(4)); // Print it with specified indentation
JSON中每个定义的字段顺序是随机的。具体的顺序取决于解析器的实现。