Deserializing ImmutableList using Gson

后端 未结 3 1704
自闭症患者
自闭症患者 2020-12-10 03:49

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 th

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-10 04:51

    @maaartinus already covered the second question, so I'll post a complementary Guava-based solution to the first question which doesn't require ParametrizedTypeImpl

    public final class ImmutableListDeserializer implements JsonDeserializer> {
      @Override
      public ImmutableList deserialize(final JsonElement json, final Type type,
                                          final JsonDeserializationContext context)
          throws JsonParseException {
        final Type[] typeArguments = ((ParameterizedType) type).getActualTypeArguments();
        final Type parameterizedType = listOf(typeArguments[0]).getType();
        final List list = context.deserialize(json, parameterizedType);
        return ImmutableList.copyOf(list);
      }
    
      private static  TypeToken> listOf(final Type arg) {
        return new TypeToken>() {}
            .where(new TypeParameter() {}, (TypeToken) TypeToken.of(arg));   
      }
    }
    

提交回复
热议问题