zoukankan      html  css  js  c++  java
  • spring boot2之Jackson和ObjectMapper

    在spring boot中,默认使用Jackson来实现java对象到json格式的序列化与反序列化。如第3篇讲的@RequestBody和@ResponseBody的转换,最终都是由Jackson来完成的。

     

    ObjectMapper基本用法

    Jackson的转换是通过ObjectMapper对象来实现的,spring boot内部自动配置了一个ObjectMapper对象,我们可以直接用。

        @Autowired
        ObjectMapper objectMapper;
        
        @GetMapping("/hello")
        public void hello() throws IOException {
            
            User user1 = new User();
            user1.setId("1");
            user1.setName("tom");
            //序列化
            String json = objectMapper.writeValueAsString(user1);
            System.out.println(json);
            
            //反序列化
            User user2 = objectMapper.readValue(json, User.class);
            System.out.println(user2.getId());
            System.out.println(user2.getName());

    writeValueAsString:是将参数中的java对象序列化为json字符串。

    readValue:是将json字符串反序列化为java对象,User.class就是指定对象的类型。

    泛型的反序列化

    上面的方法同样适用于集合类型,但如果是包含泛型的集合则需要使用以下两种方法之一
            String json = "[{"id":"1","name":"tom"},{"id":"2","name":"jerry"}]";
            JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, User.class);
            List<User> list = objectMapper.readValue(json, javaType);

    或者

            String json = "[{"id":"1","name":"tom"},{"id":"2","name":"jerry"}]";
            List<User> list = objectMapper.readValue(json, new TypeReference<List<User>>() {})

     

    properties常用参数配置

    #日期类型格式
    spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
    #日期类型使用中国时区
    spring.jackson.time-zone=GMT+8
    #序列化所有参数
    spring.jackson.default-property-inclusion=always

    spring.jackson.date-format:当序列化对象中包含日期类型的参数时,配置其转换的格式,如yyyy-MM-dd HH:mm:ss

    spring.jackson.time-zone:有些日期数据可能并不是中国时区,设置GMT+8可将其转换为中国时区

    spring.jackson.default-property-inclusion:需要进行序列化的参数,默认值为always指所有。还可配置如下值:

        non_null:为null的参数不序列化。
        non_empty:为空的参数不序列化,如""、null、没有内容的new HashMap()等都算。Integer的0不算空。
        non_default:为默认值的参数不序列化,以上都算。另外,如Integer的0等也算默认值。

    不序列化的参数:指java对象转换为json字符串时,其中不包含该参数。如当id=1,name=null时,always默认序列化为

    如配置了不序列化为null的值,结果如下

     

    常用注解

    @JsonProperty:如下,假如id=1,转换为json时将输出key=1

    @JsonProperty("key")
    Integer id

    @JsonIgnore:如下,不序列化id参数

    @JsonIgnore
    Integer id;
  • 相关阅读:
    僵尸进程与孤儿进程/守护进程/互斥锁
    基于udp协议支持并发的套接字/并发相关的概念/开启进程的两种方式/进程对象的方法
    python3和python2的区别
    安装python
    浅谈aiohttp和middlewares
    IO多路复用之select,poll,epoll个人理解
    python之进程,线程,协程简单理解
    Python类__call__()方法
    python中str与bytes
    测试理论基础三
  • 原文地址:https://www.cnblogs.com/Kerryworld/p/12470523.html
Copyright © 2011-2022 走看看