Using Spring Boot 2.6.4
, I am trying to tweak the behavior of the @RequestBody
to parse json requests with or without Root elements without writing boilerplate code in the same controller class.
//should emulate the behaviour of the ObjectMapper when the property is set as 'spring.jackson.deserialization.UNWRAP_ROOT_VALUE=false'
@PostMapping(value = "/method") public void method1(@RequestBody SomeObject someObject) {
}
//should emulate the behaviour of the ObjectMapper when the property is set as 'spring.jackson.deserialization.UNWRAP_ROOT_VALUE=true'
@PostMapping(value = "/method")
public void method1(@RequestBody SomeObject someObject) {
}
This is the boilerplate option.
@PostMapping(value = "/method2")
public void method(@RequestBody String jsonString) {
try {
ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
SomeObject someObject = mapper.readValue(jsonString, SomeObject.class);
//proceed to business logic
} catch (JsonProcessingException jsonProcessingException) {
}