杰克逊并没有去序列化它已经序列化的通用列表
2022-09-03 05:15:12
当使用Apache Jersey和Jackson进行JSON序列化(在服务器和客户端上)时,我在取消泛型列表时遇到了一个问题。
我正在生成的JSON如下所示,“data”中的所有3个类都实现了“CheckStatusDetail”:
{
"errorCode" : 0,
"errorMessage" : null,
"type" : "array",
"data" : [ {
"@class" : "com.rrr.base.status.module.dto.DiscoveryAgentCheckStatusDetail",
"serverInfo" : {
"@class" : "com.rrr.base.util.discovery.config.xml.XMLServerInfo",
"name" : "java",
"location" : "THEO",
"description" : "sddgs",
"group" : "java",
"aliases" : [ "mercury" ]
}
}, {
"@class" : "com.rrr.base.status.module.dto.MongoDBCheckStatusDetail",
"addresses" : [ "localhost:27017" ],
"version" : "2.5",
"connected" : true
}, {
"@class" : "com.rrr.base.status.module.dto.NetworkCheckStatusDetail",
"splitBrain" : false
} ],
"count" : 3,
"status" : 0
}
生成此 JSON 的对象如下所示,我在客户端使用相同的类:
public class NSResponse<T> implements Serializable {
private static final long serialVersionUID = 1L;
public static final int STATUS_OK = 0;
public static final int STATUS_ERROR = -1;
public static final String TYPE_OBJECT = "object";
public static final String TYPE_ARRAY = "array";
private int status;
private int errorCode;
private String errorMessage;
private String type;
private List<T> data;
private int count;
public NSResponse() { }
public NSResponse(int errorCode, String errorMessage) {
this.status = STATUS_ERROR;
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}
public NSResponse(T data) {
this.status = STATUS_OK;
this.type = TYPE_OBJECT;
this.data = new ArrayList<T>();
this.data.add(data);
this.count = this.data.size();
}
public NSResponse(List<T> data) {
this.status = STATUS_OK;
this.type = TYPE_ARRAY;
this.data = data;
this.count = (data == null) ? 0 : data.size();
}
/* Getters and setters omitted */
}
自从我将此注释添加到我的 CheckStatusDetail 界面以来,正在应用@class信息:
@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class")
public interface CheckStatusDetail extends Serializable {}
尝试在客户端使用 JSON 时,我收到以下错误:
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.rrr.base.status.module.dto.CheckStatusDetail
此错误发生在我第一次尝试访问“数据”字段后,它被取消。如果我调试客户端,Jackson似乎返回一个List<LinkedHashMap>,这解释了错误,因为我需要一个List<CheckStatusDetail>。
我做错了什么?