我正在尝试用Gson反序列化RSAPublicKey
,但它不能按照我的意愿工作。 Gson首先抱怨,因为它说RSAPublicKey
没有no-arg构造函数,所以我创建了一个InstanceCreator
:
public static class PublicKeyInstanceCreator implements InstanceCreator<RSAPublicKey> {
public RSAPublicKey createInstance(final Type type) {
try {
final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048);
final KeyPair key = keyGen.generateKeyPair();
return (RSAPublicKey) key.getPublic();
} catch (final NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
}
并在创建Gson对象时注册它
Gson gson = new GsonBuilder().registerTypeAdapter(RSAPublicKey.class, new PublicKeyInstanceCreator()).create();
现在Gson似乎运行正常,但是从解析Json文件创建的RSAPublicKey
对象是从RSAPublicKey
返回的任何PublicKeyInstanceCreator
对象,即字段永远不会更改反序列化过程。如何让Gson正确返回我想要的对象?