使用Gson反序列化ImmutableList

使用Gson反序列化ImmutableList

本文介绍了使用Gson反序列化ImmutableList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了很多不可变的集合,我很好奇如何使用Gson反序列化它们。由于没有人回答,我自己找到了解决方案,我正在简化问题并提出自己的答案。



我有两个问题:




  • 如何为所有 ImmutableList< XXX>写入一个反序列化程序 ?

  • 如何为所有 ImmutableList< XXX> ?
  • 注册

解决方案

更新:,其中涵盖了许多番石榴集合:


  • ImmutableList

  • ImmutableSet

  • ImmutableSortedSet

  • ImmutableMap

  • ImmutableSortedMap






这部分是微不足道的,注册的第一个参数是 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 all ImmutableList<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

The idea is simple, transform the passed Type representing an ImmutableList<T> into a Type representing List<T>, use the build-in Gson's capability to create a List and convert it to an ImmutableList.

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 with sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl.

That part is trivial, the first argument to register is java.lang.reflect.Type which mislead me to using ParameterizedType, where simply using Class does the job:

final Gson gson = new GsonBuilder()
    .registerTypeAdapter(ImmutableList.class, myJsonDeserializer)
    .create();

这篇关于使用Gson反序列化ImmutableList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 10:25