@JsonRootName 无法与 @RequestBody 一起使用

问题描述 投票:0回答:1

在此输入图像描述 我保证输入的 json 字符串是相同的,但是 @RequestBody 周围的 Dto 字段始终为 null;

版本 JDK8,17 springboot2.0,3.3 杰克逊2.11,2.14

输入字符串

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

应用程序.yml

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

我尝试添加一个wrapperDTO来替换@JsonRootName 但是还有其他明确的方法可以使 @JsonRootName 工作吗? 如果 @JsonRootName 与 @RequestBody 配合良好,它可以防止我编辑太多代码。

json spring-boot request controller jackson
1个回答
0
投票

您的配置使用了错误的属性。

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

spring.serialization
不是有效的属性。您想要使用的是
spring.jackson.serialization
属性。

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

这应该有效。

有关用于 JSON 配置的属性列表,请参阅文档。有关 Jackson 特定的更多信息,您可以查看文档的这一部分,其中还详细解释了使用什么属性来做什么。

© www.soinside.com 2019 - 2024. All rights reserved.