【问题标题】:Gson generic collection of interfaceGson 通用接口集合
【发布时间】:2014-06-04 12:59:41
【问题描述】:

我有以下方法以Serializable为自定义接口:

private <T extends Synchronizable> Collection<T> deserialize(String json, Class<T> type) {
  Type collectionType = new TypeToken<ArrayList<T>>(){}.getType();
  return new Gson().fromJson(json, collectionType);
}

此方法无法正常工作,因为 Gson 期望类型标记是特定的泛型类型,例如Type collectionType = new TypeToken&lt;ArrayList&lt;Group&gt;&gt;(){}.getType();(而Group 实现Serializable)。

有没有人知道这个问题的解决方案,或者我不能在这个地方使用泛型方法,这会很尴尬。

【问题讨论】:

标签: java generics serialization deserialization gson


【解决方案1】:

您应该使用您在其中接受的type 参数,如:

  private <T extends Synchronizable> Collection<T> deserialize(String json, Class<T> type){
        Type collectionType = new TypeToken<ArrayList<Class<T>>>(){}.getType();
         return new Gson().fromJson(json, collectionType);
  }

【讨论】:

  • 由于type无法解析为类型而无法编译。
  • @Benny 然后使用原始的Class&lt;T&gt;。查看我的更新
  • 然后gson会尝试反序列化一个Class类型。
猜你喜欢
  • 1970-01-01
  • 2020-01-27
  • 1970-01-01
  • 1970-01-01
  • 2011-09-18
  • 2012-03-07
  • 2014-10-17
  • 1970-01-01
  • 2013-01-23
相关资源
最近更新 更多