这是一个重复的问题,因为以下问题要么很混乱,要么根本没有答案:
jackson-deserialize-into-runtime-specified-class
我希望这个问题最终能找到一个答案,让这个问题永远清晰。
有一个模型:
public class AgentResponse<T> {
private T result;
public AgentResponse(T result) {
this.result = result;
}
public T getResult() {
return result;
}
}
JSON输入:
{"result":{"first-client-id":3,"test-mail-module":3,"third-client-id":3,"second-client-id":3}}
以及两种反序列化泛型类型的推荐方法:
mapper.readValue(out, new TypeReference<AgentResponse<Map<String, Integer>>>() {});
或者
JavaType javaType = mapper.getTypeFactory().constructParametricType(AgentResponse.class, Map.class);
mapper.readValue(out, javaType);
Jackson 永远无法处理泛型类型 T,它认为它是来自 JavaType 的 Map,但由于类型擦除,它找到了 Object 类型的构造函数参数并引发错误。那么这是杰克逊的错误,还是我做错了什么?TypeReference 或 JavaType 的显式规范还有什么用途?
com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class com.fg.mail.smtp.AgentResponse<java.util.Map<java.lang.String,java.lang.Integer>>]: can not instantiate from JSON object (need to add/enable type information?)
at [Source: java.io.InputStreamReader@4f2d26d; line: 1, column: 2]
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:164)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:984)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:276)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:121)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2888)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2064)