我有一个界面:
//@JsonDeserialize(as = ProjectEditor.class)
//@JsonDeserialize(using = ProjectEditorDeserializer.class)
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "className")
//@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")|
public interface IProjectEditor extends Serializable{
并且我试图调用作为输入IProjectEditor对象获取的rest api方法:
@Override
public void fabricate(IProjectEditor projectEditor, String fabConfigName)
throws FabricationException, SpecificationException {
Invocation.Builder builder = baseTarget.path(apiPath + "/fabricate").queryParam("fabConfigName", fabConfigName).request(MediaType.APPLICATION_JSON);
try {
Response response = builder.post(Entity.json(projectEditor));
checkResponseErrors(response);
} catch (InternalErrortException e) {
throw new FabricationException(e.getMessage());
}
}
但是我遇到以下错误:
无法阅读文档:无法构造.... IProjectEditor的实例,问题:抽象类型要么需要映射到具体类型,要么具有自定义反序列化器,要么被其他类型信息实例化 在[来源:java.io.PushbackInputStream@f493da4;行:1,列:1];嵌套的异常是com.fasterxml.jackson.databind.JsonMappingException:无法构造.... IProjectEditor的实例,问题:抽象类型要么需要映射到具体类型,要么具有自定义反序列化器,或者使用其他类型信息实例化 在[来源:java.io.PushbackInputStream@f493da4;行:1,列:1]
我尝试了以下几篇文章中的指示:
Cannot construct instance of - Jackson
How to deserialize interface fields using Jackson's objectMapper?
https://www.baeldung.com/jackson-exception
https://hzhou.me/2015/04/23/Jackson-deserialize-nested-object/
但仍然不能为我工作!
我尝试做一个外部Deserializer,但是它将需要更改组件结构和移动类。.IProjectEditor在一个组件中,而实现它的ProjectEditor在另一个组件中...但是编写Deserializer时,需要它们和导致它们之间发生重定向(循环关系):
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import ...IProjectEditor;
import ...ProjectEditor;
public class ProjectEditorDeserializer extends JsonDeserializer<IProjectEditor> {
@Override
public IProjectEditor deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException {
ProjectEditor result = null;
ObjectCodec oc = jsonParser.getCodec();
JsonNode node = oc.readTree(jsonParser);
ObjectMapper mapper = new ObjectMapper();
for (JsonNode n : node) {
result = mapper.treeToValue(n, ProjectEditor.class);
}
return result;
}
}