2

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) {
    }
  • I think [this](https://stackoverflow.com/a/37243185/7681514) answer to a similar question might cover what you're asking for – Matt Mar 21 '22 at 20:01
  • I'd like to see the @RequestBody behave differently, that means the jackson mapper will read the root elements whenever needed. The configuration for the jackson mapper should be per method – Benjamin E.Ndugga Mar 22 '22 at 08:12
  • My immediate thought is that this isn't possible without forcing springboot to use your own custom-defined ObjectMapper on a per-method basis (which would be interesting to know if it were possible). I believe spring has its own single `objectMapper` in the spring container that it uses for all JSON parsing, and since the unwrap root value feature is a boolean, it could not be changed on the fly and be expected to work consistently. – Matt Mar 22 '22 at 12:50
  • I believe Spring has the "@Qualifier" that distinguishes the beans of the same type. If this feature can be supported on the "@RequestBody" it will be good. Do we have a developer forum for spring, I could post the same question there – Benjamin E.Ndugga Mar 25 '22 at 07:23

0 Answers0