使用Gson反序列化ImmutableList [英] Deserializing ImmutableList using Gson
问题描述
我使用了很多不可变的集合,我很好奇如何使用Gson反序列化它们。由于没有人回答,我自己找到了解决方案,我正在简化问题并提出自己的答案。
我有两个问题:
- 如何为所有
ImmutableList< XXX>写入一个
?反序列化程序
- 如何为所有
ImmutableList< XXX>
? 注册
更新: https://github.com/acebaggins/gson-serializers ,其中涵盖了许多番石榴集合:
ImmutableList
ImmutableSet
ImmutableSortedSet
ImmutableMap
ImmutableSortedMap
如何编写适用于所有ImmutableList的单个Deserializer?
这个想法很简单,将表示
ImmutableList< T> $的
类型 c $ c>转换为
类型
代表List< T>
,使用内置Gson
创建List
并将其转换为ImmutableList
的功能。class MyJsonDeserializer实现了JsonDeserializer< ImmutableList<>> {
@Override
public ImmutableList<?> JSONDeserializationContext上下文throws JsonParseException {
final类型type2 = ParameterizedTypeImpl.make(List.class,((ParameterizedType)type).getActualTypeArguments(),null);
final List<?> list = context.deserialize(json,type2);
返回ImmutableList.copyOf(list);
$ b $ParameterizedTypeImpl
我使用的Java库中的类,但没有一个用于公共用途。我使用sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl
来测试它。
为所有ImmutableList注册它?
这部分是微不足道的,注册的第一个参数是
java.lang .reflect.Type
误导我使用ParameterizedType
,其中简单地使用Class
作业:
$ $ p $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $。$ b .create();
I'm using quite a few immutable collections and I'm curious how to deserialize them using Gson. As nobody answered and I've found the solution myself, I'm simplifying the question and presenting my own answer.
I had two problems:
- How to write a single
Deserializer
working for allImmutableList<XXX>
?- How to register it for all
ImmutableList<XXX>
?解决方案Update: There's https://github.com/acebaggins/gson-serializers which covers many guava collections:
ImmutableList
ImmutableSet
ImmutableSortedSet
ImmutableMap
ImmutableSortedMap
How to write a single Deserializer working for all ImmutableList?
The idea is simple, transform the passed
Type
representing anImmutableList<T>
into aType
representingList<T>
, use the build-inGson
's capability to create aList
and convert it to anImmutableList
.class MyJsonDeserializer implements JsonDeserializer<ImmutableList<?>> { @Override public ImmutableList<?> deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { final Type type2 = ParameterizedTypeImpl.make(List.class, ((ParameterizedType) type).getActualTypeArguments(), null); final List<?> list = context.deserialize(json, type2); return ImmutableList.copyOf(list); } }
There are multiple
ParameterizedTypeImpl
classes in Java libraries I use, but none of them intended for public usage. I tested it withsun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl
.How to register it for all ImmutableList?
That part is trivial, the first argument to register is
java.lang.reflect.Type
which mislead me to usingParameterizedType
, where simply usingClass
does the job:final Gson gson = new GsonBuilder() .registerTypeAdapter(ImmutableList.class, myJsonDeserializer) .create();
这篇关于使用Gson反序列化ImmutableList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!