Reputation: 1112
I have following class which is basically response from web service.
public class WSGenericMessage<T> implements Serializable {
private static final long serialVersionUID = 1L;
private Boolean ResponseCode;
private String ResponseMessage;
private Class<T> ResponseData;
public Boolean getResponseCode() {
return ResponseCode;
}
public void setResponseCode(Boolean responseCode) {
ResponseCode = responseCode;
}
public String getResponseMessage() {
return ResponseMessage;
}
public void setResponseMessage(String responseMessage) {
ResponseMessage = responseMessage;
}
public Class<T> getResponseData() {
return ResponseData;
}
public void setResponseData(Class<T> responseData) {
ResponseData = responseData;
}
}
Is it possible to deserialize json string in following way:
Gson gson = new Gson();
Type type = new TypeToken<WSGenericMessage<String>>(){}.getType();
gson.fromJson(result, type);
I am getting:
java.lang.UnsupportedOperationException: Attempted to deserialize a java.lang.Class. Forgot to register a type adapter?
Upvotes: 1
Views: 2479
Reputation: 22847
There's something like type erasure, so generic types are erased and not available in runtime.
So you can deserialize object giving class without generic classifiers, and than 'cast' to proper type.
But you problem is not the generic types deserialization, but the type that contains java.lang.Class
object. This can't be serialized and deserialized.
For serialization and deserialization you should use objects without Class field, use String field with class name, or mark this field as transient
and restore it afterwards.
Upvotes: 1