在 Java 中的 Jackson JSON 反序列化期间忽略缺少的属性 [英] Ignore missing properties during Jackson JSON deserialization in Java
本文介绍了在 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 反序列化期间忽略缺少的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文