@JsonIgnoreProperties(ignoreUnknown = false)在Spring 4.2.0和更高版本中不起作用 [英] @JsonIgnoreProperties(ignoreUnknown=false) is not working in Spring 4.2.0 and upper version
问题描述
@JsonIgnoreProperties(ignoreUnknown = false)在spring 4.2.0和spring的更高版本中不起作用.但是它正在使用4.0.4和4.0.1. 我正在使用Spring 4.2.8,并使用了Jackson依赖项
@JsonIgnoreProperties(ignoreUnknown=false) is not working with spring 4.2.0 and upper version of spring. But it is working with 4.0.4 and 4.0.1 . I am using spring 4.2.8 and Jackson dependencies are used
<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请求,则它被接受为有效请求.但是它应该给出错误的请求作为响应. 例如:如果我上课
If I send json request with invalid fields then it is accepting as a valid request. But it should give the bad request as response. For example: If I have class
public class Student{
private String id;
private String name;
}
如果发送有效的对应json请求,则应为
If send valid corresponding json request it should be like
{
"id": "123",
"name": "test"
}
但是,即使我发送带有无效字段(如下所示)的json请求,它仍然可以接受.
But even if I send json request with invalid fields like below it is still accepting.
{
"id": "123",
"name": "test",
"anyinvalidkey": "test"
}
但是它应该给出错误的请求作为响应
But it should give the bad request as response
推荐答案
基于注释的基于Aarya答案的解决方案可以通过以下方式完成:
An annotation based solution to the based on the answer from Aarya can done in the following way:
@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);
}
}
这篇关于@JsonIgnoreProperties(ignoreUnknown = false)在Spring 4.2.0和更高版本中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!