• json----fastjson的使用,jackson的使用



    教程地址

    一、简介

    官网:https://www.json.org/json-zh.html

    二、使用场景

    • 网络传输

      描述同样的信息,JSON相比xml占用更少的空间。

      
      <person>
      	<id>1id>
        <name>张三name>
        <age>30age>
      person>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6

      json表示:

      {
        "id":1,
        "name":"张三",
        "age":30
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
    • 序列化存储

    三、java里操作JSON有哪些技术?

    • 所谓的操作

      把java里面的bean、map、collection等转为json字符串(序列化)或反向操作(反序列化)。

    • java里面操作json的技术一览

    image-20220817122950571

    四、fastjson

    <dependency>
      <groupId>com.alibabagroupId>
      <artifactId>fastjsonartifactId>
      <version>1.2.73version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    4.1 序列化

    快速入门

    实体类创建

    @Data
    public class Person {
        /**
         * 用户ID
         */
        private Long id;
        private String name;
        private String pwd;
        /**
         * 地址
         */
        private String addr;
        /**
         * 网站
         */
        private String websiteUrl;
        private Date registerDate;
        private LocalDateTime birthDay;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    测试类

    @Test
    public void test01() {
        Person person = new Person();
        person.setId(0L);
        person.setName("张三");
        person.setPwd("1234");
        person.setAddr("北京");
        person.setWebsiteUrl("www.zhangsan.com");
        person.setRegisterDate(new Date());
        person.setBirthDay(LocalDateTime.now());
    
        String jsonstr = JSON.toJSONString(person);
        System.out.println(jsonstr);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    测试结果

    {"addr":"北京","birthDay":"2022-08-23T23:51:51.634","id":0,"name":"张三","pwd":"1234","registerDate":1661269911525,"websiteUrl":"www.zhangsan.com"}
    
    • 1

    问题:

    1. 任意属性为空时,序列化后会被忽略
    2. Date日期格式不是想要的
    3. LocalDateTime格式也不是想要的

    序列化的枚举介绍

    SerializerFeature 枚举常量,做序列化的个性需求,是可变参数

    SerializerFeature.WriteMapNullValue : 序列化时包含null的值

    SerializerFeature.WriteNullNumberAsZero : 枚举的常量,序列化自动为值为null,序列化为0

    SerializerFeature.WriteNullBooleanAsFalse : 枚举常量,序列化,布尔值为null,序列化为false

    SerializerFeature.WriteDateUseDateFormat : 枚举常量,序列化,日期的格式化 , 后面可以在字段注解中处理

    SerializerFeature.PrettyFormat :枚举常量,序列化,美化输出,美化输出也有另一种,会在后面介绍 String jsonstr = JSON.toJSONString(list,true);

    入门中的问题

    1.如何包含null的字段
        @Test
        public void test02() {
            Person person = new Person();
            person.setId(0L);
            person.setName("张三");
    //        person.setPwd("1234");
            person.setAddr("北京");
            person.setWebsiteUrl("www.zhangsan.com");
            person.setRegisterDate(new Date());
            person.setBirthDay(LocalDateTime.now());
    
            /*
            WriteMapNullValue:指定序列化时包含null
             */
            String jsonstr = JSON.toJSONString(person,SerializerFeature.WriteMapNullValue);
            System.out.println(jsonstr);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    {"addr":"北京","birthDay":"2022-08-23T23:57:10.589","id":0,"name":"张三","pwd":null,"registerDate":1661270230399,"websiteUrl":"www.zhangsan.com"}
    
    • 1
    2.日期格式
    @Data
    public class Person {
      
    		//略...
        
        @JSONField(format = "yyyy-MM-dd HH:mm:ss")
        private Date registerDate;
        @JSONField(format = "yyyy-MM-dd HH:mm:ss")
        private LocalDateTime birthDay;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    {"addr":"北京","birthDay":"2022-08-24 00:01:04","id":0,"name":"张三","pwd":"1234","registerDate":"2022-08-24 00:01:04","websiteUrl":"www.zhangsan.com"}
    
    {"addr":"北京","birthDay":"2022-08-24 00:01:28","id":0,"name":"张三","pwd":null,"registerDate":"2022-08-24 00:01:28","websiteUrl":"www.zhangsan.com"}
    
    • 1
    • 2
    • 3
    3.$ref

    引用探测

    @Test
    public void test03() {
        List<Person> list = new ArrayList<>();
        Person person = new Person();
        person.setId(0L);
        person.setName("张三");
        person.setAddr("北京");
        person.setWebsiteUrl("www.zhangsan.com");
        list.add(person);
        list.add(person);
        list.add(person);
    
        String jsonstr = JSON.toJSONString(list);
        System.out.println(jsonstr);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    [{"addr":"北京","id":0,"name":"张三","websiteUrl":"www.zhangsan.com"},{"$ref":"$[0]"},{"$ref":"$[0]"}]
    
    • 1

    禁用引用探测

    @Test
    public void test04() {
        List<Person> list = new ArrayList<>();
        Person person = new Person();
        person.setId(0L);
        person.setName("张三");
        person.setAddr("北京");
        person.setWebsiteUrl("www.zhangsan.com");
        list.add(person);
        list.add(person);
        list.add(person);
    
        String jsonstr = JSON.toJSONString(list,SerializerFeature.DisableCircularReferenceDetect);
        System.out.println(jsonstr);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    [{"addr":"北京","id":0,"name":"张三","websiteUrl":"www.zhangsan.com"},{"addr":"北京","id":0,"name":"张三","websiteUrl":"www.zhangsan.com"},{"addr":"北京","id":0,"name":"张三","websiteUrl":"www.zhangsan.com"}]
    
    • 1

    可以指定多个序列化器

    @Test
    public void test04() {
        List<Person> list = new ArrayList<>();
        Person person = new Person();
        person.setId(0L);
        person.setName("张三");
        person.setAddr("北京");
        person.setWebsiteUrl("www.zhangsan.com");
        list.add(person);
        list.add(person);
        list.add(person);
    
        String jsonstr = JSON.toJSONString(list,SerializerFeature.DisableCircularReferenceDetect,SerializerFeature.WriteMapNullValue);
        System.out.println(jsonstr);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    [{"addr":"北京","birthDay":null,"id":0,"name":"张三","pwd":null,"registerDate":null,"websiteUrl":"www.zhangsan.com"},{"addr":"北京","birthDay":null,"id":0,"name":"张三","pwd":null,"registerDate":null,"websiteUrl":"www.zhangsan.com"},{"addr":"北京","birthDay":null,"id":0,"name":"张三","pwd":null,"registerDate":null,"websiteUrl":"www.zhangsan.com"}]
    
    • 1
    4.SerializeFilter定制处理

    对属性或属性值在序列化前做定制化处理

        @Test
        public void test05() {
            Person person = new Person();
            person.setId(0L);
            person.setName("张三");
    //        person.setPwd("1234");
            person.setAddr("北京");
            person.setWebsiteUrl("www.zhangsan.com");
            person.setRegisterDate(new Date());
            person.setBirthDay(LocalDateTime.now());
    
            /*
            object: person对象
            name: 属性
            value: name属性对应的值
             */
            NameFilter nameFilter = (object,name,value) -> name.toUpperCase();
            String jsonstr = JSON.toJSONString(person,nameFilter);
            System.out.println(jsonstr);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    {"ADDR":"北京","BIRTHDAY":"2022-08-24T00:17:13.472","ID":0,"NAME":"张三","REGISTERDATE":1661271433376,"WEBSITEURL":"www.zhangsan.com"}
    
    • 1
    5.美化格式输出
    //美化格式输出
    String str = JSON.toJSONString(obj,true);
    
    • 1
    • 2
    @Test
    public void test08() {
        List<Person> list = new ArrayList<>();
        Person person = new Person();
        person.setId(0L);
        person.setName("张三");
        person.setAddr("北京");
        person.setWebsiteUrl("www.zhangsan.com");
        list.add(person);
        list.add(person);
        list.add(person);
    
        String jsonstr = JSON.toJSONString(list,true);
        System.out.println(jsonstr);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    [
    	{
    		"addr":"北京",
    		"id":0,
    		"name":"张三",
    		"websiteUrl":"www.zhangsan.com"
    	},
    	{"$ref":"$[0]"},
    	{"$ref":"$[0]"}
    ]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    4.2 反序列化

    简单使用

    @Test
    public void test06() {
        String str = "{\"addr\":\"北京\",\"birthDay\":\"2022-08-24 00:01:28\",\"id\":0,\"name\":\"张三\",\"pwd\":null,\"registerDate\":\"2022-08-24 00:01:28\",\"websiteUrl\":\"www.zhangsan.com\"}";
        Person person = JSON.parseObject(str, Person.class);
        System.out.println(person);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    Person(id=0, name=张三, pwd=null, addr=北京, websiteUrl=www.zhangsan.com, registerDate=Wed Aug 24 00:01:28 CST 2022, birthDay=2022-08-24T00:01:28)
    
    • 1

    泛型返回

    @Data
    public class ResultVO<T> {
    
        private Boolean success = Boolean.TRUE;
        private T data;
        private ResultVO() {}
    
        public static <T> ResultVO<T> buildSuccess(T t) {
            ResultVO<T> resultVO = new ResultVO<>();
            resultVO.setData(t);
            return resultVO;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
        @Test
        public void test07() {
            String str = "{\"addr\":\"北京\",\"birthDay\":\"2022-08-24 00:01:28\",\"id\":0,\"name\":\"张三\",\"pwd\":null,\"registerDate\":\"2022-08-24 00:01:28\",\"websiteUrl\":\"www.zhangsan.com\"}";
            Person person = JSON.parseObject(str, Person.class);
    
            //返回调用端resultvo
            ResultVO<Person> personResultVO = ResultVO.buildSuccess(person);
            String voJsonStr = JSON.toJSONString(personResultVO);
    
    
            //窎远端吧voJsonStr反序列化为对象
            //反序列化后不能够获取到泛型类型
    //        ResultVO resultVO = JSON.parseObject(voJsonStr, ResultVO.class);
    //        System.out.println(resultVO);
    //        Object data = resultVO.getData();
    
            ResultVO<Person> deSerializedVo = JSON.parseObject(voJsonStr, new TypeReference<ResultVO<Person>>(){});
            System.out.println(deSerializedVo);
            Person data = deSerializedVo.getData();
            System.out.println(data);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    ResultVO(success=true, data=Person(id=0, name=张三, pwd=null, addr=北京, websiteUrl=www.zhangsan.com, registerDate=Wed Aug 24 00:01:28 CST 2022, birthDay=2022-08-24T00:01:28))
    Person(id=0, name=张三, pwd=null, addr=北京, websiteUrl=www.zhangsan.com, registerDate=Wed Aug 24 00:01:28 CST 2022, birthDay=2022-08-24T00:01:28)
    
    • 1
    • 2

    fastjson 对JSON中存在,实体类中不存在的key默认的处理就是忽略处理

    4.3 通用配置

    1. 指定属性名和JSON key的对应关系

    @JSONField(name = "userName")
    private String name;
    
    
    //序列化时忽略某字段,参考
    https://www.cnblogs.com/pcheng/p/11507901.html
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    2. 忽略序列化某字段

    @JSONField(serialize = false,deserialize = false)
    private String pwd;
    
    • 1
    • 2

    4.4 注解介绍

    @JSonField注解

    该注解作用域方法上,字段上,参数上。 可在序列化和反序列化时进行特性功能定制

    • 注解属性:name 【序列化|反序列化】 的名字

    • 注解属性:ordinal 【序列化】后的顺序 ,值越小,顺序越靠前

    • 注解属性:format 【序列化|反序列化】 的日期格式

    • 注解属性:serialize 【序列化】是否序列化该字段

    • 注解属性:deserialize 【反序列化】是否反序列化该字段

    • 注解属性:serialzeFeatures 【序列化】序列化时的特性定义

    @JSONType注解

    该注解作用域类上,对该类的字段进行序列化和反序列化时的特性功能定制

    • 注解属性:includes 要被序列化的字段,如includes = {"id","name","add"}
    • 注解属性:orders 要被序列化的字段的顺序,如orders = {"name","age","add","id"}

    4.5 spring 中将springmvc的JSON工具换成fastjson

    image-20220902232128481

    4.6 springboot中使用fastjson

    spring.http.converters.preferred-json-mapper=fastjson
    
    • 1
    @Bean
        public HttpMessageConverters fastJsonHttpMessageConverters(){
            //1、先定义一个convert转换消息的对象
            FastJsonHttpMessageConverter fastConverter=new FastJsonHttpMessageConverter();
            //2、添加fastjson的配置信息,比如是否要格式化返回的json数据;
            FastJsonConfig fastJsonConfig=new FastJsonConfig();
            fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
            //附加:处理中文乱码
            List<MediaType> fastMedisTypes = new ArrayList<MediaType>();
            fastMedisTypes.add(MediaType.APPLICATION_JSON_UTF8);
            fastConverter.setSupportedMediaTypes(fastMedisTypes);
            //3、在convert中添加配置信息
            fastConverter.setFastJsonConfig(fastJsonConfig);
            HttpMessageConverter<?> converter=fastConverter;
            return new HttpMessageConverters(converter);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    五、jackson

    <dependency>
      <groupId>com.fasterxml.jackson.coregroupId>
      <artifactId>jackson-databindartifactId>
    dependency>
    
    <dependency>
      <groupId>com.fasterxml.jackson.datatypegroupId>
      <artifactId>jackson-datatype-jsr310artifactId>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    import lombok.Data;
    
    import java.time.LocalDateTime;
    import java.util.Date;
    
    @Data
    public class Person {
        private Long id;
        private String name;
        private String pwd;
    
        private String addr;
    
        private String websiteUrl;
        private Date registerDate;
        private LocalDateTime birthDay;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    5.1 序列化

    快速入门

    @Test
    public void test01() throws JsonProcessingException {
        Person person = new Person();
        person.setId(0L);
        person.setName("张三");
        person.setAddr("北京");
        person.setWebsiteUrl("www.zhangsan.com");
        person.setRegisterDate(new Date());
        person.setBirthDay(LocalDateTime.now());
    
        String jsonStr = new ObjectMapper().writeValueAsString(person);
        System.out.println(jsonStr);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    {“id”:0,“name”:“张三”,“pwd”:null,“addr”:“北京”,“websiteUrl”:“www.zhangsan.com”,“registerDate”:1662122499126,“birthDay”:{“year”:2022,“month”:“SEPTEMBER”,“dayOfMonth”:2,“dayOfWeek”:“FRIDAY”,“dayOfYear”:245,“monthValue”:9,“hour”:20,“minute”:41,“second”:39,“nano”:206000000,“chronology”:{“calendarType”:“iso8601”,“id”:“ISO”}}}

    配置序列化时只包含非空属性(全局配置)

        private static ObjectMapper objectMapper = new ObjectMapper();
        static {
            //配置序列化时只包含非空属性
            objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        }
    
    
        @Test
        public void test02() throws JsonProcessingException {
            Person person = new Person();
            person.setId(0L);
            person.setName("张三");
            person.setAddr("北京");
            person.setWebsiteUrl("www.zhangsan.com");
            person.setRegisterDate(new Date());
            person.setBirthDay(LocalDateTime.now());
    
            String jsonStr =objectMapper.writeValueAsString(person);
            System.out.println(jsonStr);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    {“id”:0,“name”:“张三”,“addr”:“北京”,“websiteUrl”:“www.zhangsan.com”,“registerDate”:1662122675845,“birthDay”:{“hour”:20,“minute”:44,“second”:35,“nano”:901000000,“dayOfYear”:245,“dayOfWeek”:“FRIDAY”,“month”:“SEPTEMBER”,“dayOfMonth”:2,“year”:2022,“monthValue”:9,“chronology”:{“id”:“ISO”,“calendarType”:“iso8601”}}}

    配置序列化时只包含非空属性(单个bean配置)

    @JsonInclude(JsonInclude.Include.NON_NULL)
    public class Person {
    
    • 1
    • 2

    时间格式化配置(单个bean配置)

    @Data
    @JsonInclude(JsonInclude.Include.NON_NULL)
    public class Person {
        private Long id;
        private String name;
        private String pwd;
    
        private String addr;
    
        private String websiteUrl;
      	//时间格式化配置
        @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
        private Date registerDate;
        @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
        private LocalDateTime birthDay;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    {“id”:0,“name”:“张三”,“addr”:“北京”,“websiteUrl”:“www.zhangsan.com”,“registerDate”:“2022-09-02 20:51:21”,“birthDay”:{“dayOfYear”:245,“dayOfWeek”:“FRIDAY”,“month”:“SEPTEMBER”,“dayOfMonth”:2,“year”:2022,“monthValue”:9,“hour”:20,“minute”:51,“second”:21,“nano”:87000000,“chronology”:{“id”:“ISO”,“calendarType”:“iso8601”}}}

    这里注意没有格式化LocaDateTime

    
    <dependency>
      <groupId>com.fasterxml.jackson.datatypegroupId>
      <artifactId>jackson-datatype-jsr310artifactId>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    private static ObjectMapper objectMapper = new ObjectMapper();
    static {
        //配置序列化时只包含非空属性
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    
        // 自动通过spi发现Jackson的module并注册
        objectMapper.findAndRegisterModules();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    {“id”:0,“name”:“张三”,“addr”:“北京”,“websiteUrl”:“www.zhangsan.com”,“registerDate”:“2022-09-02 20:55:28”,“birthDay”:“2022-09-02 20:55:28”}

    image-20220902211536171

    时间格式化配置(全局配置)

    private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    private static ObjectMapper objectMapper = new ObjectMapper();
    static {
        //配置序列化时只包含非空属性
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    
        // 自动通过spi发现Jackson的module并注册
        // objectMapper.findAndRegisterModules();
    
    
        //全局配置LocalDateTime的格式
        //手动配置javaTimeModule并注册
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT)));
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT)));
        //注册
        objectMapper.registerModule(javaTimeModule);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    image-20220902212613280

    美化输出

    //美化输出
    objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    
    • 1
    • 2

    {
    “id” : 0,
    “name” : “张三”,
    “addr” : “北京”,
    “websiteUrl” : “www.zhangsan.com”,
    “registerDate” : “2022-09-02 21:28:04”,
    “birthDay” : “2022-09-02 21:28:05”
    }

    5.2 反序列化

    简单使用

    @Test
    public void test03() throws IOException {
        String jsonstr = "    {\n" +
                "        \"id\" : 0,\n" +
                "            \"name\" : \"张三\",\n" +
                "            \"addr\" : \"北京\",\n" +
                "            \"websiteUrl\" : \"www.zhangsan.com\",\n" +
                "            \"registerDate\" : \"2022-09-02 21:28:04\",\n" +
                "            \"birthDay\" : \"2022-09-02 21:28:05\"\n" +
                "    }";
    
        Person person = objectMapper.readValue(jsonstr, Person.class);
        System.out.println(person);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    JSON中存在实体类不存在的key

    @Test
    public void test03() throws IOException {
        String jsonstr = "    {\n" +
                "        \"id\" : 0,\n" +
                "            \"name\" : \"张三\",\n" +
                //添加实体类中不存在的属性
                "            \"age\" : \"18\",\n" +
                "            \"addr\" : \"北京\",\n" +
                "            \"websiteUrl\" : \"www.zhangsan.com\",\n" +
                "            \"registerDate\" : \"2022-09-02 21:28:04\",\n" +
                "            \"birthDay\" : \"2022-09-02 21:28:05\"\n" +
                "    }";
    
        Person person = objectMapper.readValue(jsonstr, Person.class);
        System.out.println(person);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field “age” (class com.zs.utilsTest.jackson.Person), not marked as ignorable (7 known properties: “addr”, “websiteUrl”, “id”, “pwd”, “registerDate”, “name”, “birthDay”])
    at [Source: (String)" {
    “id” : 0,
    “name” : “张三”,
    “age” : “18”,
    “addr” : “北京”,
    “websiteUrl” : “www.zhangsan.com”,
    “registerDate” : “2022-09-02 21:28:04”,
    “birthDay” : “2022-09-02 21:28:05”
    }"; line: 4, column: 22] (through reference chain: com.zs.utilsTest.jackson.Person[“age”])

    需要添加配置

    //忽略JSON串中的key在实体类中不存在的key
    //objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
    objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    
    • 1
    • 2
    • 3

    对于泛型的处理

    @Test
    public void test05() throws IOException {
        Person person = new Person();
        person.setId(0L);
        person.setName("aaa");
        person.setPwd("");
        person.setAddr("");
        person.setWebsiteUrl("");
        person.setRegisterDate(new Date());
        person.setBirthDay(LocalDateTime.now());
    
        ResultVO<Person> personResultVO = ResultVO.buildSuccess(person);
        String personJson = objectMapper.writeValueAsString(personResultVO);
    
        ResultVO<Person> resultVO = objectMapper.readValue(personJson, new TypeReference<ResultVO<Person>>() {
        });
    
        System.out.println(resultVO.getData());
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    5.3 通用配置

    序列化:驼峰转下划线,反序列化:下划线转驼峰

    //驼峰转下划线
    objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
    
    • 1
    • 2

    指定属性和json字符串key对应关系

    @JsonProperty("address")
    private String addr;
    
    • 1
    • 2

    忽略指定属性

    @JsonIgnore
    private String pwd;
    
    • 1
    • 2

    其他应用

    对象更新

    对象更新:对象的合并/重写,如果后者有值用后者,否则前者的值不变

    @Test
    public void test06() throws IOException {
        Person person = new Person();
        person.setId(0L);
        person.setName("aaa");
        person.setAddr("上海");
    
        Person person2 = new Person();
        person2.setId(2L);
        person2.setAddr("北京");
        person2.setRegisterDate(new Date());
    
        Person updatePerson = objectMapper.updateValue(person,person2);
        System.out.println(updatePerson);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    Person(id=2, name=aaa, pwd=null, addr=北京, websiteUrl=null, registerDate=Fri Sep 02 22:07:58 CST 2022, birthDay=null)

    所有文件

    package com.zs.utilsTest.jackson;
    
    import com.alibaba.fastjson.JSON;
    import com.fasterxml.jackson.annotation.JsonInclude;
    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.core.type.TypeReference;
    import com.fasterxml.jackson.databind.DeserializationFeature;
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    import com.fasterxml.jackson.databind.PropertyNamingStrategy;
    import com.fasterxml.jackson.databind.SerializationFeature;
    import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
    import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
    import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
    
    import com.zs.utilsTest.json.domain.ResultVO;
    import org.junit.Test;
    
    import java.io.IOException;
    import java.text.SimpleDateFormat;
    import java.time.LocalDateTime;
    import java.time.format.DateTimeFormatter;
    import java.util.Date;
    
    public class JacksonTest {
        private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
        private static ObjectMapper objectMapper = new ObjectMapper();
        static {
            //配置序列化时只包含非空属性
            objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    
            // 自动通过spi发现Jackson的module并注册
            // objectMapper.findAndRegisterModules();
    
            // 对Date进行配置,SimpleDateFormat是线程不安全的
            objectMapper.setDateFormat(new SimpleDateFormat(DATE_TIME_FORMAT));
    
            //全局配置LocalDateTime的格式
            //手动配置javaTimeModule并注册
            JavaTimeModule javaTimeModule = new JavaTimeModule();
            javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT)));
            javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT)));
            //注册
            objectMapper.registerModule(javaTimeModule);
    
    
            //美化输出
            objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    
            //忽略JSON串中的key在实体类中不存在的key
            //objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
            objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    
    
            //驼峰转下划线
            objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
        }
    
    
        @Test
        public void test06() throws IOException {
            Person person = new Person();
            person.setId(0L);
            person.setName("aaa");
            person.setAddr("上海");
    
            Person person2 = new Person();
            person2.setId(2L);
            person2.setAddr("北京");
            person2.setRegisterDate(new Date());
    
            Person updatePerson = objectMapper.updateValue(person,person2);
            System.out.println(updatePerson);
        }
    
    
        @Test
        public void test05() throws IOException {
            Person person = new Person();
            person.setId(0L);
            person.setName("aaa");
            person.setPwd("");
            person.setAddr("");
            person.setWebsiteUrl("");
            person.setRegisterDate(new Date());
            person.setBirthDay(LocalDateTime.now());
    
            ResultVO<Person> personResultVO = ResultVO.buildSuccess(person);
            String personJson = objectMapper.writeValueAsString(personResultVO);
    
            ResultVO<Person> resultVO = objectMapper.readValue(personJson, new TypeReference<ResultVO<Person>>() {
            });
    
            System.out.println(resultVO.getData());
        }
    
    
        @Test
        public void test04() throws IOException {
            String jsonstr = "    {\n" +
                    "        \"id\" : 0,\n" +
                    "            \"name\" : \"张三\",\n" +
                    //添加实体类中不存在的属性
                    "            \"age\" : \"18\",\n" +
                    "            \"addr\" : \"北京\",\n" +
                    "            \"websiteUrl\" : \"www.zhangsan.com\",\n" +
                    "            \"registerDate\" : \"2022-09-02 21:28:04\",\n" +
                    "            \"birthDay\" : \"2022-09-02 21:28:05\"\n" +
                    "    }";
    
            Person person = objectMapper.readValue(jsonstr, Person.class);
            System.out.println(person);
        }
    
        @Test
        public void test03() throws IOException {
            String jsonstr = "    {\n" +
                    "        \"id\" : 0,\n" +
                    "            \"name\" : \"张三\",\n" +
                    //添加实体类中不存在的属性
                    "            \"age\" : \"18\",\n" +
                    "            \"addr\" : \"北京\",\n" +
                    "            \"websiteUrl\" : \"www.zhangsan.com\",\n" +
                    "            \"registerDate\" : \"2022-09-02 21:28:04\",\n" +
                    "            \"birthDay\" : \"2022-09-02 21:28:05\"\n" +
                    "    }";
    
            Person person = objectMapper.readValue(jsonstr, Person.class);
            System.out.println(person);
        }
    
    
    
        @Test
        public void test02() throws JsonProcessingException {
            Person person = new Person();
            person.setId(0L);
            person.setName("张三");
            person.setAddr("北京");
            person.setWebsiteUrl("www.zhangsan.com");
            person.setRegisterDate(new Date());
            person.setBirthDay(LocalDateTime.now());
    
            String jsonStr =objectMapper.writeValueAsString(person);
            System.out.println(jsonStr);
        }
    
    
    
        @Test
        public void test01() throws JsonProcessingException {
            Person person = new Person();
            person.setId(0L);
            person.setName("张三");
            person.setAddr("北京");
            person.setWebsiteUrl("www.zhangsan.com");
            person.setRegisterDate(new Date());
            person.setBirthDay(LocalDateTime.now());
    
            String jsonStr = new ObjectMapper().writeValueAsString(person);
            System.out.println(jsonStr);
        }
    
    
    
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    package com.zs.utilsTest.jackson;
    
    
    import com.fasterxml.jackson.annotation.JsonFormat;
    import com.fasterxml.jackson.annotation.JsonIgnore;
    import com.fasterxml.jackson.annotation.JsonInclude;
    import com.fasterxml.jackson.annotation.JsonProperty;
    import lombok.Data;
    
    import java.time.LocalDateTime;
    import java.util.Date;
    
    @Data
    @JsonInclude(JsonInclude.Include.NON_NULL)
    public class Person {
        private Long id;
        private String name;
        @JsonIgnore
        private String pwd;
    
        @JsonProperty("address")
        private String addr;
    
        private String websiteUrl;
        @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
        private Date registerDate;
        @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
        private LocalDateTime birthDay;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    package com.zs.utilsTest.json.domain;
    
    import com.sun.org.apache.xpath.internal.operations.Bool;
    import com.zs.domain.Result;
    import lombok.Data;
    
    
    @Data
    public class ResultVO<T> {
    
        private Boolean success = Boolean.TRUE;
        private T data;
        private ResultVO() {}
    
        public static <T> ResultVO<T> buildSuccess(T t) {
            ResultVO<T> resultVO = new ResultVO<>();
            resultVO.setData(t);
            return resultVO;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
  • 相关阅读:
    数聚携手永达汽车集团强势入选爱分析《商业智能实践案例》
    企业微信主体怎么转让给别人?
    【Linux】标准输出和异常输出
    React中实现插槽效果的方案
    QML包管理
    常用消息中间件
    十七、SpringAMQP
    PCIE1—快速实现PCIE接口上下位机通信(一)
    跨平台开发:在Linux上构建Windows应用程序
    Python基础——递归及其经典例题(阶乘、斐波那契数列、汉诺塔)
  • 原文地址:https://blog.csdn.net/weixin_44235759/article/details/126672039