使用 Gson 反序列化 ImmutableList
我正在使用相当多的不可变集合,我很好奇如何使用 Gson 反序列化它们。由于没有人回答并且我自己找到了解决方案,因此我正在简化问题并提出我自己的答案。
我有两个问题:
- 如何编写一个适用于所有
ImmutableList
的Deserializer
? - 如何为所有
ImmutableList
注册它?
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>
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
更新:https://github.com/acebaggins/gson-serializers涵盖了许多番石榴集合:
ImmutableList
ImmutableSet
ImmutableSortedSet
ImmutableSortedMap
ImmutableSortedMap
想法很简单,将传递的表示
ImmutableList
的Type
转换为表示List
的Type
>,使用内置的Gson
功能创建List
并将其转换为ImmutableList
。我使用的 Java 库中有多个 ParameterizedTypeImpl 类,但它们都不供公共使用。我使用
sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl
对其进行了测试。这部分很简单,注册的第一个参数是 java.lang.reflect.Type,它误导我使用 ParameterizedType,而只是使用 Class做的工作:
Update: There's https://github.com/acebaggins/gson-serializers which covers many guava collections:
ImmutableList
ImmutableSet
ImmutableSortedSet
ImmutableMap
ImmutableSortedMap
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
.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
.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:另一种没有 ParameterizedTypeImpl 的实现
One more implementation without ParameterizedTypeImpl
@maaartinus 已经涵盖了第二个问题,因此我将针对第一个问题发布一个基于 Guava 的补充解决方案,该解决方案不需要
ParametrizedTypeImpl
@maaartinus already covered the second question, so I'll post a complementary Guava-based solution to the first question which doesn't require
ParametrizedTypeImpl