Jackson中处理map中的null key 或者null value 及实体字段中的null value

1.map中有null key时的序列化

 当有null key时,jackson序列化会报 Null key for a Map not allowed in JSON (use a converting NullKeySerializer?) 

处理此异常有两种方式

  • 1.需要自定义一个序列化null key的方法
  • 2. map中直接remove null key

这里只讨论第一种:

处理方法为 mapper.getSerializerProvider().setNullKeySerializer(new NullKeySerializer()); 将null key处理为空字符

    @Test
    public void testSerializMapNullKey() throws JsonProcessingException {
        //ignore map null value
        Map<String, Object> map = new HashMap<>();
        map.put(null, "test");
        ObjectMapper mapper = new ObjectMapper();
        mapper.getSerializerProvider().setNullKeySerializer(new NullKeySerializer());
        System.out.println(mapper.writeValueAsString(map));

    }

static class NullKeySerializer extends StdSerializer<Object> {
        public NullKeySerializer() {
            this(null);
        }

        public NullKeySerializer(Class<Object> t) {
            super(t);
        }

        @Override
        public void serialize(Object nullKey, JsonGenerator jsonGenerator, SerializerProvider unused)
                throws IOException, JsonProcessingException {
            jsonGenerator.writeFieldName("");
        }
    }
{"":"test"}

Process finished with exit code 0

2. 处理null value的情况

    @Test
    public void testIgnoreMapNullValue() throws JsonProcessingException {
        //ignore null key
        Map<String, Object> map = new HashMap<>();
        map.put("key", "test");
        map.put("key1", null);
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        System.out.println(mapper.writeValueAsString(map));

    }

输出为:{"key":"test"} 并没有 key1:null

{"key":"test"}

Process finished with exit code 0

3. 处理实体中filed中值为null的情况

使用注解:@JsonInclude(JsonInclude.Include.NON_NULL)

注意:@JsonInclude(JsonInclude.Include.NON_NULL)即可以在实体上用,也可以在filed中使用,比如在name上用这个注解

    @Test
    public void testIgnoreNullFiled() throws JsonProcessingException {
        //test ignore null filed
        User user = new User();
        user.setName(null);
        user.setHouse("asdf");
        ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.writeValueAsString(user));

    }

    /**
     * ignore null filed
     */
    @JsonInclude(JsonInclude.Include.NON_NULL)
    class User {
        private String name;
        private String house;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getHouse() {
            return house;
        }

        public void setHouse(String house) {
            this.house = house;
        }
    }

输出为:

{"house":"asdf"}

Process finished with exit code 0

如果设置全局怎么设置呢,使用: mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    @Test
    public void testIgnoreNullFiledGlobally() throws JsonProcessingException {
        //test ignore null filed
        User user = new User();
        user.setName(null);
        user.setHouse("asdf");
        ObjectMapper mapper = new ObjectMapper();

        //Ignore Null Fields Globally
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        System.out.println(mapper.writeValueAsString(user));

    }

参考:1.https://www.baeldung.com/jackson-map-null-values-or-null-key

         2.https://github.com/eugenp/tutorials/tree/master/jackson-simple

原文地址:https://www.cnblogs.com/guanbin-529/p/11441061.html

时间: 2024-07-31 19:52:50

Jackson中处理map中的null key 或者null value 及实体字段中的null value的相关文章

向数据库中插入一个DateTime类型的数据到一个Date类型的字段中,需要转换类型。TO_DATE(&#39;{0}&#39;,&#39;YYYY-MM-DD&#39;))

需要指出的是,C#中有datetime类型,但是这个类型是包括小时,分钟,秒的.这个格式与数据库中的Date类型不符,如果将now设为datetime类型插入数据会失败. 需要通过TO_DATE('字段','YYYY-MM-DD'))转换.如下: string.Format("insert into tablename (TIME) values(TO_DATE('{0}','YYYY-MM-DD'))",now) 错误写法: string.Format("insert in

foreach属性-动态-mybatis中使用map类型参数,其中key为列名,value为列值

http://www.cnblogs.com/anruy/p/5942044.html Integer updateA(@Param("A") Map<String, Double> A); <update id="updateA" parameterType="java.util.Map"> <foreach collection="A.keys" item="key" in

mysql 允许在唯一索引的字段中出现多个null值

线上问题:org.springframework.dao.DuplicateKeyException: PreparedStatementCallback; SQL [update fl_table set id = ?, password = ?, email = ? where id = '3583954800']; Duplicate entry ' ' for key 'email'; nested exception is com.mysql.jdbc.exceptions.jdbc4

mysql 中查询一个字段是否为null的sql

查询mysql数据库表中字段为null的记录: select * 表名 where 字段名 is null 查询mysql数据库表中字段不为null的记录: select * 表名 where 字段名 is not null 例如: select * from table where column is null; select * from table where column is not null;

Java中Map根据键值(key)或者值(value)进行排序实现

我们都知道,java中的Map结构是key->value键值对存储的,而且根据Map的特性,同一个Map中 不存在两个Key相同的元素,而value不存在这个限制.换句话说,在同一个Map中Key是唯一的,而value不唯一.Map是一个接口,我们不能 直接声明一个Map类型的对象,在实际开发中,比较常用的Map性数据结构是HashMap和TreeMap,它们都是Map的直接子类.如果考虑到存取 效率的话,建议使用HashMap数据结构,而如果需要考虑到Key的顺序,建议使用TreeMap,但是

JAVA中遍历Map和Set方法,取出map中所有的key

Java遍历Set集合 1.迭代器遍历: Set<String> set = new HashSet<String>(); Iterator<String> it = set.iterator(); while (it.hasNext()) { String str = it.next(); System.out.println(str); } 2.for循环遍历: for (String str : set) { System.out.println(str); }

JavaScript中获取Map集合中的key和value值(前提是:既不知道key为什么值,也不知道value有哪些值)

for(var i in maps){//通过定义一个局部变量i遍历获取map里面的所有key值 alert(maps[i]); //通过获取key对应的value值 }

javascript中使用Map

mis.comm.js.Map = function() { this.elements = new Array(); //获取MAP元素个数 this.size = function() { return this.elements.length; } //推断MAP是否为空 this.isEmpty = function() { return (this.elements.length < 1); } //删除MAP全部元素 this.clear = function() { this.el

list中含有map的排序问题

Map的种类 在Java中,Map的主要作用是存储键值对.由于是根据键得到值,所以不允许键重复.它主要有如下几个类别: HashMap: 最常用的Map,它根据键的HashCode值存储数据,根据键可以直接获取它的值,具有很快的访问速度,遍历时,取得数据的顺序是完全随机的.HashMap最多只允许一条记录的键为Null;允许多条记录的值为Null;HashMap不支持线程的同步,即任一时刻可以有多个线程同时写HashMap;可能会导致数据的不一致.如果需要同步,可以用Collections的sy