Java:jackson实现json缩进美化输出

依赖


<dependency>
    <groupId>com.fasterxml.jackson.coregroupId>
    <artifactId>jackson-databindartifactId>
    <version>2.10.0version>
dependency>

代码实现

public class JsonUtil {
    /**
     * 美化输出
     */
    public static void prettyPrint(Object obj) {
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
            System.out.println(json);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
}

输出控制的json示例

{
  "id" : 9,
  "username" : "Panda",
  "password" : "abcd",
  "age" : 20,
  "gender" : "男",
  "email" : "[email protected]"
}

参考
【数据格式】Jackson 美化输出JSON,优雅的输出JSON数据,格式化输出JSON数据

你可能感兴趣的:(Java学习路线,java,json,开发语言)