Java LocalDate与Gson序列化报错InaccessibleObjectException排查
问题:LocalDate序列化JSON时抛出权限异常且自定义适配器未生效
我尝试将包含LocalDate字段的类转换为JSON字符串时,始终出现以下错误:
Caused by: java.lang.reflect.InaccessibleObjectException: Unable to make field private final int java.time.LocalDate.year accessible: module java.base does not "opens java.time" to unnamed module @197ac685
我已查阅资料并注册了自定义适配器:
public class GsonLocalDateAdapter implements JsonSerializer<LocalDate>, JsonDeserializer<LocalDate> { private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); @Override public LocalDate deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException { return LocalDate.parse(json.getAsString(), formatter); } @Override public JsonElement serialize(LocalDate src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(src.format(formatter)); } } var gson = new GsonBuilder() .registerTypeAdapter(LocalDateTime.class, new GsonLocalDateAdapter()) .create(); var json = gson.toJson(myObject);
但序列化方法的断点从未触发,请问我遗漏了什么?
解决方案
核心问题:适配器注册类型不匹配
你编写的适配器是针对LocalDate类型的,但注册时却传入了LocalDateTime.class,这导致Gson不会用该适配器处理LocalDate字段,仍然会默认通过反射访问LocalDate的私有成员,进而抛出权限错误,适配器的断点自然也不会触发。修复步骤
修改GsonBuilder的注册代码,确保类型匹配:var gson = new GsonBuilder() .registerTypeAdapter(LocalDate.class, new GsonLocalDateAdapter()) .create();额外提示
如果项目中还需要处理LocalDateTime类型,建议单独编写对应的适配器;或者直接引入Gson官方的gson-java8扩展依赖,它内置了所有Java 8时间类型的序列化/反序列化逻辑,无需手动编写适配器。
内容的提问来源于stack exchange,提问作者Maxim
相关产品推荐
相关产品推荐

