2016-07-26 68 views
0

查看Stackoverflow问题后,我找不到解决此问题的任何解决方案。java.lang.ClassCastException:com.google.gson.internal.LinkedTreeMap无法转换为模型

我试图使用GSON并实施这样的通用方法:

public <T> List<T> deserializeList(String json) { 
    Gson gson = new Gson(); 
    Type type = (new TypeToken<List<T>>() {}).getType(); 
    return gson.fromJson(json, type); 
} 

调用此方法是通过这样做:

parser.<Quote>deserializeList(result) 

不过,我得到的结果是这样的:

enter image description here

当我我试图访问一个对象,我得到这个错误:

java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to model.Quote 

的JSON字符串是:

[ 
    { 
     "id": 269861, 
     "quote": "People living deeply have no fear of death.", 
     "author": "Anais Nin", 
     "genre": "life", 
     "tag": null, 
     "createdAt": "2016-04-16T13:13:36.928Z", 
     "updatedAt": "2016-04-16T13:13:36.928Z" 
    } 
] 
+0

我不认为这就是你应该如何调用类型参数 –

+0

@ cricket_007有没有关系 - parser.deserializeList(result) – codebased

+0

这就是我的想法。现在,类定义中的T是什么?第二个问题,你可以使用Retrofit吗? –

回答

1

我想你可以写的方法,像这样明确地提供Type

public <T> List<T> deserializeList(String json, Type type) { 
    Gson gson = new Gson(); 
    return gson.fromJson(json, type); 
} 

虽然,通过(new TypeToken<List<Model>>() {}).getType();看起来有点凌乱。

我不太熟悉类型擦除,但我敢打赌,这与问题有关。

相关问题