You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Gson自定义PublicKey序列化器未触发,引发反射访问异常的问题求助

Gson自定义PublicKey序列化器未触发,引发反射访问异常的问题求助

大家好,最近在项目里遇到一个Gson序列化的坑,折腾半天没搞定,来请教下各位大佬!

我的实现代码

首先,我为java.security.PublicKey写了一个自定义序列化器:

public class PublicKeySerializer implements JsonSerializer<PublicKey> {
    @Override
    public JsonElement serialize(PublicKey key, Type type, JsonSerializationContext context) {
        System.out.println("Serialize Public Key");
        JsonObject result = new JsonObject();
        // 这里是后续的序列化处理逻辑
        return result;
    }
}

然后在Spring的组件里注册这个序列化器:

@Component
public class JsonSerializer {
    private Gson gson;

    @PostConstruct
    public void init() {
        this.gson = new GsonBuilder()
                .registerTypeAdapter(PublicKey.class, new PublicKeySerializer())
                .create();
    }

    public Gson getGson() {
        return gson;
    }
}

最后在另一个业务组件里调用:

JsonElement json = this.jsonSerializer.getGson().toJsonTree(publicKey);

遇到的问题

按道理说,调用toJsonTree的时候应该触发我写的自定义序列化器才对,但实际情况是——完全没触发!控制台连我加的Serialize Public Key日志都没打出来,反而直接抛出了反射访问的异常:

com.google.gson.JsonIOException: Failed making field 'sun.security.rsa.RSAPublicKeyImpl#n' accessible; either increase its visibility or write a custom TypeAdapter for its declaring type.
    at com.google.gson.internal.reflect.ReflectionHelper.makeAccessible(ReflectionHelper.java:76) ~[gson-2.13.1.jar:na]
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:391) ~[gson-2.13.1.jar:na]
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:165) ~[gson-2.13.1.jar:na]
    at com.google.gson.Gson.getAdapter(Gson.java:628) ~[gson-2.13.1.jar:na]
    at com.google.gson.Gson.toJson(Gson.java:928) ~[gson-2.13.1.jar:na]
    at com.google.gson.Gson.toJsonTree(Gson.java:802) ~[gson-2.13.1.jar:na]
    at com.google.gson.Gson.toJsonTree(Gson.java:779) ~[gson-2.13.1.jar:na]

更奇怪的是,我用Jackson做完全一样的自定义序列化配置,是可以正常触发的,但项目有其他限制,必须用Gson。另外我的项目是Spring Boot非Web项目,只用到了Spring的依赖注入等基础特性。

求助

有没有大佬知道为什么Gson不肯触发我的自定义序列化器?应该怎么调整才能解决这个问题?

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.09 03:03:09