fix: 修复 JDK17+ 环境下测试用例 PagingAndSortingQueryParamsTests#testGson 不通过的问题

该用例在 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
This commit is contained in:
zhouxy108 2025-04-16 14:52:02 +08:00
parent c779430e6f
commit 45dc105dd0

View File

@ -184,8 +184,6 @@ public class PagingAndSortingQueryParamsTests {
assertThrows(IllegalArgumentException.class, queryParams::buildPagingParams); assertThrows(IllegalArgumentException.class, queryParams::buildPagingParams);
} }
static final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
@Test @Test
void testGson() { void testGson() {
Gson gson = new GsonBuilder() Gson gson = new GsonBuilder()
@ -193,15 +191,27 @@ public class PagingAndSortingQueryParamsTests {
@Override @Override
public void write(JsonWriter out, LocalDate value) throws IOException { public void write(JsonWriter out, LocalDate value) throws IOException {
out.value(dateFormatter.format(value)); out.value(DateTimeFormatter.ISO_DATE.format(value));
} }
@Override @Override
public LocalDate read(JsonReader in) throws IOException { 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<LocalDateTime>() {
@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(); .create();
try (SqlSession session = sqlSessionFactory.openSession()) { try (SqlSession session = sqlSessionFactory.openSession()) {
AccountQueryParams params = gson.fromJson(JSON_STR, AccountQueryParams.class); AccountQueryParams params = gson.fromJson(JSON_STR, AccountQueryParams.class);
@ -212,6 +222,7 @@ public class PagingAndSortingQueryParamsTests {
List<AccountVO> list = accountQueries.queryAccountList(params, pagingParams); List<AccountVO> list = accountQueries.queryAccountList(params, pagingParams);
long count = accountQueries.countAccount(params); long count = accountQueries.countAccount(params);
PageResult<AccountVO> accountPageResult = PageResult.of(list, count); PageResult<AccountVO> accountPageResult = PageResult.of(list, count);
log.info(gson.toJson(accountPageResult)); log.info(gson.toJson(accountPageResult));
assertEquals(Lists.newArrayList( assertEquals(Lists.newArrayList(