Jackson 美化输出JSON,优雅的输出JSON数据,格式化输出JSON数据... ...
一下用了这么多形容词,就是怕你们找不到。Jackson 美化输出JSON,优雅的输出JSON数据,格式化输出JSON数据
其实本站的第一个工具,也就是首页的,就是JSON格式化输出,但是增加了校验功能,以及中文提示问题所在。比如如下 JSON 少了一个“,”。
好了,介绍完毕,开始走代码吧。
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>测试类请在附件中下载。
版权所属:SO JSON在线解析
原文地址:https://www.sojson.com/blog/245.html
转载时必须以链接形式注明原始出处及本声明。
如果本文对你有帮助,那么请你赞助我,让我更有激情的写下去,帮助更多的人。
