如何调整 Spring MVC 或 @RequestBody 行为来解析带有或不带有根元素的 json 文件
使用 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论