【数据格式】Jackson 美化输出JSON,优雅的输出JSON数据,格式化输出JSON数据 您所在的位置:网站首页 怎么美化文档格式内容 【数据格式】Jackson 美化输出JSON,优雅的输出JSON数据,格式化输出JSON数据

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

2024-06-27 17:09| 来源: 网络整理| 查看: 265

在这里插入图片描述

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引入:

com.fasterxml.jackson.core jackson-databind 2.7.4 com.fasterxml.jackson.core jackson-core 2.7.4 com.fasterxml.jackson.core jackson-annotations 2.7.4

测试类请在附件中下载。



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有