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

1.概述

转载:https://www.sojson.com/blog/245.html

Jackson 格式化输出JSON 代码说明(对象)
我们一般输出就是普通的toString 输出。如下代码:

Demo demo = new Demo("sojson",4,"https://www.sojson.com");
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(demo));

输出结果:

{"name":"sojson","age":4,"domain":"https://www.sojson.com"}

非常不利于肉眼观看,而且一大坨,如果是JSON很大的话,那么更难受。那么我们美化输出呢?

美化/优雅/格式化输出,代码如下:

public static void main(String[] args) throws JsonProcessingException {
    Demo demo = new Demo("sojson",4,"https://www.sojson.com");
    ObjectMapper mapper = new ObjectMapper();
    //普通输出
    System.out.println(mapper.writeValueAsString(demo));
    //格式化/美化/优雅的输出
    System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(demo));
}

输出结果:

{
  "name" : "sojson",
  "age" : 4,
  "domain" : "https://www.sojson.com"
}

是不是结果很nice?下面再看下字符串输出。

Jackson 格式化输出JSON 代码说明(字符)
其实这里就是把字符串转成对象(Object ),然后再输出的。

优雅输出 Java代码:

public static void main(String[] args) throws IOException {
   //已知一个json 字符串
    String json = "{\"name\":\"sojson\",\"age\":4,\"domain\":\"https://www.sojson.com\"}";
    //求优雅输出
    ObjectMapper mapper = new ObjectMapper();
    Object obj = mapper.readValue(json, Object.class);
    System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj));
}

输出结果:

{
  "name" : "sojson",
  "age" : 4,
  "domain" : "https://www.sojson.com"
}

这里有的同学是不是想到,如果直接用上面的方法(writerWithDefaultPrettyPrinter() )呢,因为参数类型是Object ,其实我看了源码,Object 是为了你方便传参为各种你的对象。如果你传的String ,那么直接出来String 了。也就是还是输出原来的方式。当然你也可以试试。

Jackson Maven引入:

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

测试类请在附件中下载。

你可能感兴趣的:(数据格式,jackson,美化输出,优雅输出,格式化)