[英]Caused by: java.lang.ClassCastException: libcore.reflect.ParameterizedTypeImpl cannot be cast to java.lang.Class when use Generic Type
I make a class extend AsyncTask to parse Json use Gson, because input can be many type of class I use generic type: 我做了一个类扩展AsyncTask来解析Json使用Gson,因为输入可以是很多类我使用泛型类:
public class ApiResponse<T> extends AsyncTask...
I need know class type of T to pass Gson with: 我需要知道T类的类型来传递Gson:
(1) (1)
Class<T> clazz =
(Class<T>)((ParameterizedType)
getClass().getGenericSuperclass())
.getActualTypeArguments()[0];
new Gson().fromJson(reader, clazz);
However, Here T can be a class that have many type so that some time I pass class: 但是,这里的T可以是一个有很多类型的类,所以有一段时间我传递类:
(2) (2)
public class DataMessage<T> implements Serializable{...}
With these class have this format I received a Exception Caused by: 有了这些类有这种格式,我收到了一个异常引起的:
java.lang.ClassCastException: libcore.reflect.ParameterizedTypeImpl cannot be cast to java.lang.Class
at (1) 在(1)
How do I do in this case ? 在这种情况下我该怎么办?
UPDATED: 更新:
public class DataMessage<T> implements Serializable{
@SerializedName("pagination")
private Pagination pagination;
@SerializedName("meta")
private Message meta;
@SerializedName("data")
private T data;
public DataMessage(T data) {
this.data = data;
}
public Pagination getPagination() {
return pagination;
}
public void setPagination(Pagination pagination) {
this.pagination = pagination;
}
public Message getMeta() {
return meta;
}
public void setMeta(Message meta) {
this.meta = meta;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public class Pagination {
@SerializedName("next_max_tag_id")
public String nextMaxTagId;
@SerializedName("deprecation_warning")
public String deprecationWarning;
@SerializedName("next_max_id")
public String nextMaxId;
@SerializedName("next_min_id")
public String nextMinId;
@SerializedName("min_tag_id")
public String minTagId;
@SerializedName("next_url")
public String nextUrl;
}
public class Message {
@SerializedName("error_type")
public String errorType;
@SerializedName("code")
public int code;
@SerializedName("error_message")
public String error_message;
}
}
When I need to parse JSON with specific class using Gson, I use GsonBuilder in this way 当我需要使用Gson解析特定类的JSON时,我以这种方式使用GsonBuilder
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
try{
return new Date( json.getAsJsonPrimitive().getAsLong()*1000L );
}catch( Exception e ){
return null;
}
}
});
Gson gson = gsonBuilder.create();
In your case I think that you can simply parse your JSON in this way: 在你的情况下,我认为你可以用这种方式解析你的JSON:
DataMessage<YourClass> dataMessage = gson.fromJson(yourJsonObj, DataMessage.class);
Another thing is that you can obtain the exact Type in this way 另一件事是你可以用这种方式获得确切的类型
Type collectionType = new TypeToken<DataMessage<T>>() {}.getType();
But probably you will get a bad Json when you deserialize this... 但是当你反序列化时,你可能会得到一个糟糕的Json ......
The best way is to use the class instead of T so Gson know exactly what has to serialie/deserialize 最好的方法是使用类而不是T,因此Gson确切知道什么必须序列化/反序列化
Type collectionType = new TypeToken<DataMessage<YourClass>>() {}.getType();
I found this for you Deserializing Generic Types with GSON 我发现这个为你用GSON反序列化通用类型
Let's say you want to deserialize a list of DataMessage<T>
using a JsonReader . 假设您要使用JsonReader反序列化
DataMessage<T>
列表。
public <T> T Gson::fromJson(JsonReader reader, Type typeOfT)
Then you have 那你有
..
import java.lang.reflect.Type; // make sure you add this import
class DataMessageList<T>
{
public List<DataMessage<T>> list;
public DataMessageList ()
{
list = null;
}
public void readJson (JsonReader reader)
{
Type TT = new TypeToken<ArrayList< DataMessage<T> >>(){}.getType();
this.list = new Gson().fromJson(reader, TT);
}
}
Thanks to @Andrea Catania with your useful help, 感谢@Andrea Catania提供的有用帮助,
Problem here is when I cast ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
这里的问题是当我转换
((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
to Class
type, With DataMessage<T>
type it can't cast. 到
Class
类型,使用DataMessage<T>
类型它无法DataMessage<T>
。
But ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]
have type is Type so that I don't need cast it to Class , I retype clazz
variable to Type (not Class ) and problem have been resolved. 但是
((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]
有类型是Type,所以我不需要把它clazz
为Class ,我重新键入clazz
变量到Type (不是Class )并且问题已经解决。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.