我在一个资源类中有一个PATCH端点,其请求体为一个抽象类。我收到了以下错误:
抛出此错误:
22:59:30 SEVERE [or.ec.ya.in.Unmarshaller] (on Line: 64) (executor-thread-63) Can't create instance
似乎因为我声明为参数的body模型是抽象的,所以反序列化失败。
我期望获得Element_A或Element_B中的任意一个。
如何声明body为多态?
这是元素层次结构。
public abstract class BaseElement {
public String name;
public Timestamp start;
public Timestamp end;
}
public class Element_A extends BaseElement{
public String A_data;
}
public class Element_B extends BaseElement{
public long B_data;
}
这是我的终端节点所用的资源类。
@Path("/myEndpoint")
public class ResourceClass {
@PATCH
@Path("/{id}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_PLAIN)
public Response updateEvent(@Valid BaseElement element, @Context UriInfo uriInfo, @PathParam long id) {
if (element instanceof Element_A) {
// Element_A logic
} else if (element instanceof Element_B) {
// Element_B logic
}
return Response.status(Response.Status.OK).entity("working").type(MediaType.TEXT_PLAIN).build();
}
}
这是我在PATCH请求中发送的请求主体
{
"name": "test",
"startTime": "2020-02-05T17:50:55",
"endTime": "2020-02-05T17:51:55",
"A_data": "it's my data"
}
我还尝试使用自定义反序列化器添加@JsonbTypeDeserializer,但未成功
@JsonbTypeDeserializer(CustomDeserialize.class)
public abstract class BaseElement {
public String type;
public String name;
public Timestamp start;
public Timestamp end;
}
public class CustomDeserialize implements JsonbDeserializer<BaseElement> {
@Override
public BaseElement deserialize(JsonParser parser, DeserializationContext context, Type rtType) {
JsonObject jsonObj = parser.getObject();
String type = jsonObj.getString("type");
switch (type) {
case "A":
return context.deserialize(Element_A.class, parser);
case "B":
return context.deserialize(Element_B.class, parser);
}
return null;
}
}
这是我发送的新请求:
{
"type": "A"
"name": "test",
"startTime": "2020-02-05T17:50:55",
"endTime": "2020-02-05T17:51:55",
"A_data": "it's my data"
}
抛出此错误:
02:33:10 SEVERE [or.ec.ya.in.Unmarshaller] (executor-thread-67) null
02:33:10 SEVERE [or.ec.ya.in.Unmarshaller] (executor-thread-67) Internal error: null
我的pom.xml包括:
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-resteasy</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-resteasy-jsonb</artifactId>
</dependency>