为什么不将Jackson设置为接受空列表为Null?

我公司有一个使用Spring的Java Web服务,该服务通过REST API接受JSON。我们还将使用Jackson 2.9版。我们试图防止当我们的API不需要一个集成器时,如果一个集成器传入一个空列表,则会引发反序列化异常。

例如,Student.java类:

@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Student {

  private String firstName;
  private String lastName;
  private Map<String, String> classGrades;
}

和预期的请求正文(JSON):

{
  "firstName": "Mark",
  "lastName": "Twain",
  "classGrades": {

  }
}

Works just fine. However, if any field (though in our specific case, the classGrades field) receives an empty list, a Jackson deserialization exception is thrown. An example JSON request that fails:

{
  "firstName": "Mark",
  "lastName": "Twain",
  "classGrades": []
}

并抛出异常:

org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of `java.util.LinkedHashMap` out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.LinkedHashMap` out of START_ARRAY token
 at [Source: (PushbackInputStream); line: 65, column: 28] 

According to the project's github page, the option ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT should resolve this issue for us. We've tried setting this directly on an ObjectMapper configuration object and within application.properties using the line:

spring.jackson.deserialization.accept-empty-array-as-null-object=true

Neither method seemed to take effect. We're currently using a workaround using the @JsonDeserialize(using = MyCustomDeserializer.class) annotaion on fields prone to this problem. However, we would like to be able to have all of our fields treat empty lists as null by default.

我们是否误解了配置选项并错误地使用了它?有没有一种方法可以在我们的应用程序中将空列表视为null;如果是,我们如何做到这一点?

评论