From 45dc105dd02f905ce938820ea234781c0718744e Mon Sep 17 00:00:00 2001 From: ZhouXY108 Date: Wed, 16 Apr 2025 14:52:02 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=20JDK17+=20=E7=8E=AF?= =?UTF-8?q?=E5=A2=83=E4=B8=8B=E6=B5=8B=E8=AF=95=E7=94=A8=E4=BE=8B=20`Pagin?= =?UTF-8?q?gAndSortingQueryParamsTests#testGson`=20=E4=B8=8D=E9=80=9A?= =?UTF-8?q?=E8=BF=87=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 该用例在 JDK17+ 环境下使用 gson 进行序列化时,报 `com.google.gson.JsonIOException: Failed making field 'java.time.LocalDateTime#date' accessible; either increase its visibility or write a custom TypeAdapter for its declaring type`。 See: https://github.com/google/gson/blob/main/Troubleshooting.md#reflection-inaccessible --- .../PagingAndSortingQueryParamsTests.java | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/src/test/java/xyz/zhouxy/plusone/commons/model/dto/test/PagingAndSortingQueryParamsTests.java b/src/test/java/xyz/zhouxy/plusone/commons/model/dto/test/PagingAndSortingQueryParamsTests.java index 8939ce6..e914d08 100644 --- a/src/test/java/xyz/zhouxy/plusone/commons/model/dto/test/PagingAndSortingQueryParamsTests.java +++ b/src/test/java/xyz/zhouxy/plusone/commons/model/dto/test/PagingAndSortingQueryParamsTests.java @@ -184,8 +184,6 @@ public class PagingAndSortingQueryParamsTests { assertThrows(IllegalArgumentException.class, queryParams::buildPagingParams); } - static final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); - @Test void testGson() { Gson gson = new GsonBuilder() @@ -193,15 +191,27 @@ public class PagingAndSortingQueryParamsTests { @Override public void write(JsonWriter out, LocalDate value) throws IOException { - out.value(dateFormatter.format(value)); + out.value(DateTimeFormatter.ISO_DATE.format(value)); } @Override public LocalDate read(JsonReader in) throws IOException { - return LocalDate.parse(in.nextString(), dateFormatter); + return LocalDate.parse(in.nextString(), DateTimeFormatter.ISO_DATE); } }) + .registerTypeAdapter(LocalDateTime.class, new TypeAdapter() { + + @Override + public void write(JsonWriter out, LocalDateTime value) throws IOException { + out.value(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(value)); + } + + @Override + public LocalDateTime read(JsonReader in) throws IOException { + return LocalDateTime.parse(in.nextString(), DateTimeFormatter.ISO_LOCAL_DATE_TIME); + } + }) .create(); try (SqlSession session = sqlSessionFactory.openSession()) { AccountQueryParams params = gson.fromJson(JSON_STR, AccountQueryParams.class); @@ -212,6 +222,7 @@ public class PagingAndSortingQueryParamsTests { List list = accountQueries.queryAccountList(params, pagingParams); long count = accountQueries.countAccount(params); PageResult accountPageResult = PageResult.of(list, count); + log.info(gson.toJson(accountPageResult)); assertEquals(Lists.newArrayList(