使用 JSON-B / Yasson 将 JSON 反序列化为多态 POJO

spa*_*kit 4 java resteasy jsonb-api yasson quarkus

我在资源类中有一个 PATCH 端点,其中一个抽象类作为请求主体。我收到以下错误:

22:59:30 SEVERE [or.ec.ya.in.Unmarshaller] (on Line: 64) (executor-thread-63) Can't create instance
Run Code Online (Sandbox Code Playgroud)

似乎因为我声明为参数的身体模型是抽象的,所以它无法反序列化。

我期待得到 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;
}
Run Code Online (Sandbox Code Playgroud)

这是我的端点的资源类

@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();
    }
}

Run Code Online (Sandbox Code Playgroud)

这是我在 PATCH 请求中发送的请求正文

{
  "name": "test",
  "startTime": "2020-02-05T17:50:55",
  "endTime": "2020-02-05T17:51:55",
  "A_data": "it's my data"
}
Run Code Online (Sandbox Code Playgroud)

我还尝试将 @JsonbTypeDeserializer 添加到自定义解串器中,但该解串器不起作用

@JsonbTypeDeserializer(CustomDeserialize.class)
public abstract class BaseElement {
    public String type;
    public String name;
    public Timestamp start;
    public Timestamp end;
}
Run Code Online (Sandbox Code Playgroud)
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;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我发送的新请求:

{
  "type": "A"
  "name": "test",
  "startTime": "2020-02-05T17:50:55",
  "endTime": "2020-02-05T17:51:55",
  "A_data": "it's my data"
}

Run Code Online (Sandbox Code Playgroud)

抛出这个错误:

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
Run Code Online (Sandbox Code Playgroud)

我的 pom.xml 包括:

<dependency>
      <groupId>io.quarkus</groupId>
      <artifactId>quarkus-resteasy</artifactId>
</dependency>
<dependency>
      <groupId>io.quarkus</groupId>
      <artifactId>quarkus-resteasy-jsonb</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)

And*_*ert 6

JSON-B 还没有对多态反序列化的理想支持,因此您现在最多可以做一种解决方法。我们在这里有一个开放的设计问题:https : //github.com/eclipse-ee4j/jsonb-api/issues/147,所以请给它一个投票+1

您对自定义反序列化器有正确的想法,但问题是您无法解析当前JsonObject然后context.deserialize()使用相同的解析器调用,因为解析器已经超出了它读取 JSON 对象的状态。(JSONParser 是一个只进解析器,所以没有办法“倒带”它)

因此,您仍然可以调用parser.getObject()您的自定义反序列化器,但是Jsonb一旦您确定了它的具体类型,您就需要使用一个单独的实例来解析该特定的 JSON 字符串。

public static class CustomDeserialize implements JsonbDeserializer<BaseElement> {

  private static final Jsonb jsonb = JsonbBuilder.create();

  @Override
  public BaseElement deserialize(JsonParser parser, DeserializationContext context, Type rtType) {

      JsonObject jsonObj = parser.getObject();
      String jsonString = jsonObj.toString();
      String type = jsonObj.getString("type");

      switch (type) {
        case "A":
          return jsonb.fromJson(jsonString, Element_A.class);
        case "B":
          return jsonb.fromJson(jsonString, Element_B.class);
        default:
          throw new JsonbException("Unknown type: " + type);
      }
  }
}
Run Code Online (Sandbox Code Playgroud)

旁注:您需要将基础对象模型更改为以下内容:

  @JsonbTypeDeserializer(CustomDeserialize.class)
  public abstract static class BaseElement {
    public String type;
    public String name;
    @JsonbProperty("startTime")
    public LocalDateTime start;
    @JsonbProperty("endTime")
    public LocalDateTime end;
  }
Run Code Online (Sandbox Code Playgroud)
  1. 假设您不能或不想更改您的 JSON 架构,您可以更改您的 java 字段名称(startend)以匹配 JSON 字段名称(startTimeendTime),或者您可以使用@JsonbProperty注释重新映射它们(我已经完成了)以上)
  2. 由于您的时间戳采用 ISO_LOCAL_DATE_TIME 格式,我建议使用java.time.LocalDateTime而不是java.sql.Timestamp因为LocalDateTime处理时区,但最终无论哪种方式都可以根据您提供的示例数据