在java中使用jackson json反序列化时忽略缺少的属性

编程入门 行业动态 更新时间:2024-10-28 21:18:18
本文介绍了在java中使用jackson json反序列化时忽略缺少的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在示例中

Class Person{ String name; int age; }

如果json对象缺少属性'age',

If the json object has a missing property 'age',

{ name : John } Person person = objectMapper.readValue(jsonFileReader, Person.class);

它会抛出一个JsonMappingException,说它不能反序列化。是否有注释在反序列化期间忽略缺失的字段?

it throws a JsonMappingException saying it cannot deserialize. Is there an annotation to ignore missing fields during deserialization ?

谢谢

推荐答案

我认为你想要的是

@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) public class Person { ... }

这是Jackson 1.x的方式。我认为在2.x中有一种新的方式。类似

that's the Jackson 1.x way. I think there's a new way in 2.x. Something like

@JsonInclude(Include.NON_NULL) public class Person { ... }

这些将告诉Jackson只序列化非空值,不要抱怨反序列化缺失值时。我认为它只会将其设置为Java默认值。

These will tell Jackson to only serialize values that are not null, and don't complain when deserializing a missing value. I think it will just set it to the Java default.

更多推荐

在java中使用jackson json反序列化时忽略缺少的属性

本文发布于:2023-08-04 05:51:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1293520.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   序列化   java   jackson   json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!