我有以下方法 Serializable
作为自定义接口(interface):
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<ArrayList<Group>>(){}.getType();
(而 Group
实现 Serializable
)。
有人知道这个问题的解决方案吗,或者我无法在这个地方使用通用方法,这会很尴尬。
最佳答案
您应该使用您在其中接受的 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);
}
关于java - Gson接口(interface)的通用集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24038170/