【问题标题】:Spring MVC: Deserialise query parameters to POJO using Jackson objectMapperSpring MVC:使用 Jackson objectMapper 将查询参数反序列化为 POJO
【发布时间】:2017-03-16 12:48:59
【问题描述】:

Spring web 应用配置包含 Jackson ObjectMapper 配置如下

  objectMapper.disable(ADJUST_DATES_TO_CONTEXT_TIME_ZONE)
  objectMapper.registerModule(new JavaTimeModule())

添加JavaTimeModule 以处理ZonedDateTime 的反序列化。有两个端点处理包含ZonedDateTime 的 POJO。 POJO是这样的:

class MyRequest {
  ZonedDateTime from
  ZonedDateTime to
}

带有端点的控制器是:

@Slf4j
@RestController
class MyController {

  @GetMapping('/pojo')
  void getPojo(MyRequest myRequest) {
    log.debug("Request received: $myRequest")
  }

  @PostMapping('/pojo')
  void postPojo(@RequestBody MyRequest myRequest) {
    log.debug("Request received: $myRequest")
  }
}

当我发送带有正文的 POST /pojo 时

{"from": "2017-03-15T00:00:00Z", "to": "2017-03-16T00:00:00Z"}

响应为200,反序列化成功。

相反,当我发送时

GET /pojo?from=2017-03-15T00:00:00Z&to=2017-03-15T00:00:00Z

收到错误的 400 Bad Request

Failed to convert from type [java.lang.String] to type [java.time.ZonedDateTime] for value '2017-03-15T00:00:00Z'

这是有道理的,因为在 GET 请求中,我没有发送 JSON,因此不会调用 JSON 对象映射器。

有没有办法将objectMapper 也用于 GET 请求,以便将查询参​​数转换为 POJO 对象?

顺便说一句,我知道它可以反序列化为如下所示的 GET 端点,但我想为 GET 和 POST 端点使用相同的转换器

@DateTimeFormat(iso = ISO.DATE_TIME)
ZonedDateTime from
@DateTimeFormat(iso = ISO.DATE_TIME)
ZonedDateTime to

【问题讨论】:

    标签: spring-mvc spring-boot deserialization jackson2


    【解决方案1】:

    注入objectMapper并将查询参数映射转换为对象解决了问题

    @Slf4j
    @RestController
    class MyController {
    
      @Autowired
      private ObjectMapper objectMapper
    
      @GetMapping('/pojo')
      void getPojo(@RequestParam Map<String, String> allRequestParams) {
        MyRequest request = objectMapper.convertValue(allRequestParams, MyRequest)
        log.debug("Request received: $myRequest")
      }
    ...
    

    【讨论】:

    • 该死!我一直在寻找这个已经快一个星期了。谢谢老哥!
    猜你喜欢
    • 2023-02-08
    • 1970-01-01
    • 2014-10-22
    • 2012-04-07
    • 2013-01-08
    • 1970-01-01
    • 1970-01-01
    • 2018-07-24
    • 1970-01-01
    相关资源
    最近更新 更多