且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

配置 Jackson 在缺少字段时抛出异常

更新时间:2023-01-16 08:05:46

很遗憾,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