简体   繁体   English

GSON反序列化通用类型

[英]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: 是否可以通过以下方式反序列化json字符串:

  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. 但是您的问题不是泛型类型反序列化,而是包含java.lang.Class对象的类型。 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. 对于序列化和反序列化,应使用不带Class字段的对象,使用带类名的String字段,或将此字段标记为transient字段,然后再将其还原。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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