@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);
}
}