我在资源类中有一个 PATCH 端点,其中一个抽象类作为请求主体。我收到以下错误:
22:59:30 SEVERE [or.ec.ya.in.Unmarshaller] (on Line: 64) (executor-thread-63) Can't create instance
似乎因为我声明为参数的身体模型是抽象的,所以它无法反序列化。
我期待得到 Element_A 或 Element_B
我怎样才能声明身体是多态的?
这是元素层次结构
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>