如何在 Restassured 请求期间转换 Instant?

How can I convert an Instant during a Restassured request?

我想执行一个放心的 GET 请求。响应包含一个对象列表,这些对象又具有 Instant 属性.

目前我得到一个异常:

com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type java.time.Instant from String "2022-03-08T20:53:02.990": Failed to deserialize java.time.Instant: (java.time.format.DateTimeParseException) Text '2022-03-08T20:53:02.990' could not be parsed at index 19 at [Source: (String)"{"timestamp":"bf105ae0-9f21-11ec-9c3e-fddae3040d6b","time":"2022-03-08T20:53:02.990","user":"XXX_SYSTEM","correlationId":"8fc84c87-aece-45b8-a7a6-66317152c840","key":"20220308_A14_0000000000000_7777777700003_5743e8cd40554a7d8110aa149e7015de_53","category":"INFO","context":"BLA","type":"BLUBB","system":true,"event":"FOO_BAR"}"; line: 1, column: 67] (through reference chain: xx.yyy.zzz.dto.MyResult$MyResultBuilder["time"])

要求:

        return given()
        .baseUri(baseUrl)
        .pathParam("aaa", value)
        .param("zeitstempelAb", FORMATTER.format(from))
        .param("zeitstempelBis", FORMATTER.format(to))
        .param("limit", "1000")
        .when()
        .log().all()
        .get("aaa/{value}")
        .then()
        .log().all()
        .assertThat()
        .statusCode(200)
        .extract()
        .body()
        .jsonPath()
        .getList("content", MyResult.class)
        ;

使用的格式化程序:

    private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
    .appendPattern("yyyy-MM-dd'T'HH:mm:ss".concat("Z"))
    .toFormatter()
    .withZone(ZoneOffset.UTC);

MyResult POJO:

@JsonDeserialize(builder = MyResult.MyResultBuilder.class)
@Value
@Builder(setterPrefix = "with")
public class MyResult {

    UUID timestamp;

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss'Z'", timezone = "UTC")
    Instant time;
    .
    .
    .
}

如何摆脱该异常?

原因:

2022-03-08T20:53:02.990 将映射到 LocalDateTime。

2022-03-08T20:53:02.990Z 将映射到 Instant。

修复:

  • 删除@JsonFormat...
  • 更改Instant time --> LocalDateTime time