zoukankan      html  css  js  c++  java
  • @JsonInclude注解,RestTemplate传输值为null的属性,利用FastJson将属性中有空值null的对象转化成Json字符串

    一个pojo类:

    import lombok.Data;
    
    @Data
    public class Friend {
        private String name;
        private int age;
        private String sex;
    }

    初始化一个Friend对象,该对象属性为"sex"对应的值设置为null:

    public class FriendTest {
        private Friend friend = new Friend();
    
        @Before
        public void init(){
            friend.setAge(26);
            friend.setName("xiaofang");
            friend.setSex(null);
        }

    使用FastJson将该对象转化为Json字符串:

    @Test
        public void testObjectToJson(){
            String jsonString = JSONObject.toJSONString(friend);
            System.out.println(jsonString);
        }

    可以看到,"sex"字段由于为null,转化时该字段没了。

    设置序列化类型

    @Test
        public void testJsonSerializer(){
            String jsonString = JSONObject.toJSONString(friend, SerializerFeature.WriteMapNullValue);
            System.out.println(jsonString);
        }

    就有值为null的属性了。

    RestTemplate传输值为null的属性

    使用RestTemplate传输该Friend对象时,值为null的属性会被忽略掉,但是我们在某些情况下想要传输值为null属性,我们可以在该字段上加上com.fasterxml.jackson.annotation.@JsonInclude注解,通过RestTemplate传输,就不会忽略值为null的属性。

  • 相关阅读:
    数据库索引分析(一)
    对象的序列化(串行化)分析(一)
    Java 集合类 TreeSet、TreeMap
    查找杀死指定进程delphi
    delphi集合的用法
    debian 删除软件
    linux 各种国内源更新 (source)
    screen 命令使用记录
    Python 常用import
    常用Python函数
  • 原文地址:https://www.cnblogs.com/theRhyme/p/10339071.html
Copyright © 2011-2022 走看看