【问题标题】:spring boot offsetDateTime in query param查询参数中的spring boot offsetDateTime
【发布时间】:2020-10-21 21:45:00
【问题描述】:

我尝试创建以下 api:

    @GetMapping("/workerslist")
    public List<Worker> getWorkersList(
            @RequestParam(name = "lastPollBefore", required = false) OffsetDateTime lastPollBefore,
            @RequestParam(name = "lastPollAfter", required = false) OffsetDateTime lastPollAfter){
        return workerService.getWorkers(lastPollBefore, lastPollAfter);
    }

但是当我调用它时,我收到以下错误:

{
  "_type": "ValidationError",
  "key": "validation-error",
  "message": "Failed to convert value of type 'java.lang.String' to required type 'java.time.OffsetDateTime'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam java.time.OffsetDateTime] for value '2020-07-01T11:52:57.152Z'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2020-07-01T11:52:57.152Z]",
  "constraints": [
    
  ]
}

我找到了 localDateTime 的解决方案,但它们似乎不适用于 offsetDateTime,

【问题讨论】:

标签: java spring


【解决方案1】:

您需要为控制器中的 OffsetDateTime 参数添加 @DateTimeFormat 注释。例如。

    @GetMapping("/workerslist")
    public List<Worker> getWorkersList(
            @RequestParam(name = "lastPollBefore", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)OffsetDateTime lastPollBefore,
            @RequestParam(name = "lastPollAfter", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)OffsetDateTime lastPollAfter){
        return workerService.getWorkers(lastPollBefore, lastPollAfter);
    }

您可能希望通过您自己的自定义映射器覆盖 Spring 的默认对象映射器。

类似这样的:

@Configuration
public class JsonConfiguration {

  private static final ObjectMapper OBJECT_MAPPER =
      new ObjectMapper().registerModule(new JavaTimeModule())
          .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
          .disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE)
          .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

  @Bean
@Primary
  public static ObjectMapper getObjectMapper() {
    return OBJECT_MAPPER;
  }
}

【讨论】:

  • 我之前尝试过@DateTimeFormat 部分,但仍然出错,更改对象映射器就可以了
猜你喜欢
  • 2021-09-15
  • 2019-12-23
  • 1970-01-01
  • 2021-06-25
  • 1970-01-01
  • 1970-01-01
  • 2021-06-16
  • 2019-10-09
  • 1970-01-01
相关资源
最近更新 更多