JSON Beautifier Library for Java

六月ゝ 毕业季﹏ 提交于 2020-03-18 04:00:33

问题


I want to format a string containing JSON data using Java. Does anybody know an open source library for that.


回答1:


Assuming you're starting out with an existing JSON string, then Jackson can do this for you:

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);

String originalJson = ...
JsonNode tree = objectMapper .readTree(originalJson);
String formattedJson = objectMapper.writeValueAsString(tree);



回答2:


Update to previous answer by skaffman, with newer versions of Jackson (2+, I think). The second line of code is now:

objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);



回答3:


With Jackson 2.6.1

String beautify(String json) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    Object obj = mapper.readValue(json, Object.class);
    return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
}

pom.xml:

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.6.1</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.6.1</version>
    </dependency>

Convert JSON String to Pretty Print JSON output using Jackson



来源:https://stackoverflow.com/questions/5457524/json-beautifier-library-for-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!