简体   繁体   中英

GSON deserializing generic type

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM