@JsonIgnoreProperties(ignoreUnknown=false) 不适用于 spring 4.2.0 和更高版本的 spring。但它适用于 4.0.4 和 4.0.1 。 我使用的是 spring 4.2.8 并使用 Jackson 依赖项
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.6.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.6.3</version>
</dependency>
如果我发送带有无效字段的 json 请求,那么它会作为有效请求接受。但它应该给出错误的请求作为响应。 例如:如果我有课
public class Student{
private String id;
private String name;
}
如果发送有效的相应 json 请求,它应该是这样的
{
"id": "123",
"name": "test"
}
但即使我发送带有如下无效字段的 json 请求,它仍然接受。
{
"id": "123",
"name": "test",
"anyinvalidkey": "test"
}
但它应该给出错误的请求作为响应
最佳答案
基于 Aarya 答案的基于注释的解决方案可以通过以下方式完成:
@Configuration
public class Config implements InitializingBean {
@Autowired
private RequestMappingHandlerAdapter converter;
@Override
public void afterPropertiesSet() throws Exception {
configureJacksonToFailOnUnknownProperties();
}
private void configureJacksonToFailOnUnknownProperties() {
MappingJackson2HttpMessageConverter httpMessageConverter = converter.getMessageConverters().stream()
.filter(mc -> mc.getClass().equals(MappingJackson2HttpMessageConverter.class))
.map(mc -> (MappingJackson2HttpMessageConverter)mc)
.findFirst()
.get();
httpMessageConverter.getObjectMapper().enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
}
}
关于spring - @JsonIgnoreProperties(ignoreUnknown=false) 在 Spring 4.2.0 及更高版本中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41128623/