配置 Jackson 在缺少字段时抛出异常 [英] Configure Jackson to throw an exception when a field is missing

查看:32
本文介绍了配置 Jackson 在缺少字段时抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堂这样的课:

public class Person {
  private String name;
  public String getName(){
    return name;
  }
}

我正在使用这样配置的 ObjectMapper:

I am using an ObjectMapper configured like this:

ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

我有一个包含这个 { "address" : "something" } 的字符串 str.请注意,json 中没有名称"字段.如果我这样做:

I have a String str that contains this { "address" : "something" }. Note that there is no "name" field in the json. If I do something like this:

mapper.readValue(str, Person.class);

然后我实际上取回了一个名称设置为 null 的 Person 对象.有没有办法将映射器配置为抛出异常,或者返回空引用而不是 Person?我希望 Jackson 将缺少字段视为失败,并且不想对结果对象的字段进行显式空检查.

then I actually get back a Person object with name set to null. Is there a way to configure the mapper to throw an exception instead, or return a null reference instead of a Person? I want Jackson to consider missing fields a failure and don't want to do explicit null checks on the resulting object's fields.

推荐答案

很遗憾,Jackson 目前不支持.

Unfortunately this is not supported by Jackson at this moment.

解决方案可能是在构造函数中添加验证.理想情况下,如果您不想将这些值序列化为 null's ,这确实意味着您根本不应该将它们作为 null(以其他方式构造).例如,

Solution could be to add validation in your constructor. As ideally if you don't want to have those values serialized as null's , it does mean you shouldn't have them as null's at all (constructed in other way). For example,

public class Person {
  private String name;
  public Person() {
     checkNotNull(name);
  }
} 

然而,这可能并不适用于所有情况,特别是如果您正在使用您的对象而不是通过序列化/反序列化.

however this might not fittable in all situations, specially if you are using your object's other than through serializing/deserializing.

虽然它们在 @JsonProperty 注释中有 required 属性,但在反序列化过程中根本不支持它,并且仅用于装饰 JSON 模式.请参阅此主题

Though they have required attribute in @JsonProperty annotation, it is not supported during deserialization at all, and has been introduced only for decorating JSON schemas. See this topic

这篇关于配置 Jackson 在缺少字段时抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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