在较早版本的Gson (<2.5.0)中,反射类型适配器用于反序列化java.util.Currency对象。所以我有这样的东西:"{"currencyCode":"USD"}“持久化在数据库中。
现在,我想将Gson升级到一个更高的版本(它引入了一个新的CurrencyTypeAdapterFactory -它不再能够反序列化我数据库中的对象)。
有没有办法强制Gson对Currency类使用相同的反射类型适配器?
发布于 2021-07-10 20:49:03
可以使用类似下面的内容为所需的类提供特定的类型适配器绑定:
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Currency.class, getCurrencyTypeAdapter());
gson = builder.create();
TypeAdapter<Currency> getCurrencyTypeAdapter() {
ConstructorConstructor constructorConstructor = new ConstructorConstructor(Collections.emptyMap());
JsonAdapterAnnotationTypeAdapterFactory jsonAdapterFactory = new JsonAdapterAnnotationTypeAdapterFactory(constructorConstructor);
ReflectiveTypeAdapterFactory reflectiveTypeAdapterFactory = new ReflectiveTypeAdapterFactory(
constructorConstructor, FieldNamingPolicy.IDENTITY, Excluder.DEFAULT, jsonAdapterFactory);
return reflectiveTypeAdapterFactory.create(new Gson(), new TypeToken<Currency>() {});
}这是一种变通方法。理想情况下,您应该修正Currency类的用法,并使用内部使用的默认类型适配器: Currency.getInstance()
https://stackoverflow.com/questions/68325343
复制相似问题