Search code examples
jsonspring-bootrequestcontrollerjackson

@JsonRootName not working with @RequestBody


enter image description here I promise input json strings are same,but The Dto's Field around @RequestBody always null;

version JDK8,17 springboot2.0,3.3 jackson 2.11,2.14

input strings

{ "user": { "name": "John Doe", "email": "[email protected]", "location": { "street": "123 Main St", "city": "Springfield" } } }
@RestController
@RequestMapping("/test")
public class TestController {
    @PostMapping(value = "/get", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public boolean getInfo(@RequestBody UserDTO userDTO) throws JsonProcessingException {

        String json = "{ \"user\": { \"name\": \"John Doe\", \"email\": \"[email protected]\", \"location\": { \"street\": \"123 Main St\", \"city\": \"Springfield\" } } }";

        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);

        UserDTO user = mapper.readValue(json, UserDTO.class);
        return true;
    }
}

application.yml

spring:
  serialization:
    WRAP_ROOT_VALUE: true
  deserialization:
    UNWRAP_ROOT_VALUE: true

I have tried add a wrapperDTO to replace the @JsonRootName but Any else clear method can make @JsonRootName work ? It can prevent me editing too much code if @JsonRootName work well with @RequestBody.


Solution

  • Your configuration is using the wrong property.

    spring:
      serialization:
        WRAP_ROOT_VALUE: true
      deserialization:
        UNWRAP_ROOT_VALUE: true
    

    spring.serialization is not a valid property. What you wanted to use was the spring.jackson.serialization property.

    spring:
      jackson:
        serialization:
          WRAP_ROOT_VALUE: true
        deserialization:
          UNWRAP_ROOT_VALUE: true
    

    This should work.

    For a list of properties to use for JSON configuration consult the documentation. For more information on Jackson specific you can check this part of the documentation which also explains a bit more about what property to use for what.