Spring Boot 1.4 Customize Internal Jackson Deserialization
Solution 1
FAIL_ON_UNKNOWN_PROPERTIES
option is true by default according to Jackson Documentation.
If you want to disable this setting you may add this option to application.properties
.
spring.jackson.deserialization.fail-on-unknown-properties = false
But in default settings it works as expected. So no need for any setting.
This is one file spring boot application:
@RestController
@SpringBootApplication
public class TestOptionApplication {
public static void main(String[] args) {
SpringApplication.run(TestOptionApplication.class, args);
}
@PostMapping("/test")
public void formTest(@RequestBody final HelloForm form) {
}
public static class HelloForm {
private String name;
public String getName() { return name; }
public void setName(final String name) { this.name = name; }
}
}
This is the integration test for testing rejection on unknown properties.
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestOptionApplicationTest {
@Autowired
private WebApplicationContext context;
@Test
public void testFailOnUnknownPropertiesOption() throws Exception {
final String text = "{\"name\": \"test\", \"title\": \"test\"}";
MockMvcBuilders
.webAppContextSetup(this.context)
.build()
.perform(post("/test").contentType(MediaType.APPLICATION_JSON).content(text))
.andExpect(status().isBadRequest());
}
}
title property is not defined. So controller sends BadRequest.
Solution 2
With Spring boot, by default, unknown properties are ignored during deserialization. In order not to ignore these properties, you can :
- Add
spring.jackson.deserialization.FAIL_ON_UNKNOWN_PROPERTIES=true
in the application.properties -
Use this bean :
@Bean public ObjectMapper objectMapper() { return Jackson2ObjectMapperBuilder .json() .featuresToEnable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .build(); }
-
Use this bean :
@Bean public Jackson2ObjectMapperBuilder objectMapperBuilder(){ Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); builder.failOnUnknownProperties(true); return builder; }
I have tested these solutions and it works so there is another problem in your code. Please, can you post your code as ask by javaguy?
Kiba
Updated on June 08, 2022Comments
-
Kiba almost 2 years
I am using
spring.jackson.deserialization.FAIL_ON_UNKNOWN_PROPERTIES=true
in theapplication.properties
to make deserialization fail on unknown properties but its not working.I even tried using :
@Bean ObjectMapper objectMapper() { return Jackson2ObjectMapperBuilder .json() .featuresToEnable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .build(); }
But this also didn't work. What am I missing?