如何调整 Spring MVC 或 @RequestBody 行为来解析带有或不带有根元素的 json 文件

发布于 01-15 18:47 字数 1033 浏览 3 评论 0原文

使用 Spring Boot 2.6.4,我尝试调整 @RequestBody 的行为来解析带有或不带有 Root 元素的 json 请求,而无需在同一控制器类中编写样板代码。

//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) {

}

这是样板选项。

@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) {
    }

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) {
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文