Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@JsonIgnoreProperties(ignoreUnknown=false) is not working in Spring 4.2.0 and upper version

@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>

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

If send valid corresponding json request it should be like

{ 
   "id": "123", 
   "name": "test" 
}

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

like image 521
Masbha Avatar asked Dec 13 '16 19:12

Masbha


1 Answers

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);
    }
}
like image 67
Michael Shemesh Avatar answered Sep 28 '22 06:09

Michael Shemesh