在Java中的Jackson JSON反序列化过程中忽略缺少的属性 [英] Ignore missing properties during Jackson JSON deserialization in Java

查看:1009
本文介绍了在Java中的Jackson JSON反序列化过程中忽略缺少的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在示例中

class Person {
   String name;
   int age;
}

如果JSON对象缺少属性年龄",则

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仅序列化不为null的值,并且在反序列化缺少的值时不会抱怨.我认为它将只是将其设置为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反序列化过程中忽略缺少的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆