替代Jacksonmixin为可变数量的子类型?

bvpmtnay  于 7个月前  发布在  其他
关注(0)|答案(1)|浏览(73)

我正在编写一个库,旨在供其他应用程序使用,包含一堆实现相同接口的类,如以下示例所示:

public interface Figure {
  // ...
}

public class Triangle implements Figure {
  // ...
}

public class Square implements Figure {
  // ...
}

public class Circle implements Figure {
  // ...
}

然后我为上面的所有类创建了一个mixin:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME)
  @JsonSubTypes({
      @JsonSubTypes.Type(Triangle.class),
      @JsonSubTypes.Type(Square.class),
      @JsonSubTypes.Type(Circle.class)
  })
  public interface FigureMixin {

  }

我可以像往常一样将这个mixin添加到ObjectMapper中:

ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(Figure.class, FigureMixin.class);

问题是库的用户可能希望提供他们自己的实现Figure的类。因此,注解方法并不合适,因为我不知道在编译时有多少JSON子类型(即实现Figure的类)。
有没有办法在运行时为所有实现公共接口的可用类注册子类型,即实现相同的mixin配置,但不使用注解?
先谢了。

ou6hu8tu

ou6hu8tu1#

the example here的启发,我能够实现所需的行为:
首先,在所有类实现的接口中使用@JsonTypeInfo

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME)
public interface Figure {
  // ...
}

然后,将我的所有类作为子类型注册到ObjectMapper中:

public void configure(final ObjectMapper mapper) {
  mapper.registerSubtypes(new NamedType(Triangle.class));
  mapper.registerSubtypes(new NamedType(Square.class));
  mapper.registerSubtypes(new NamedType(Circle.class));
}

当然,如果需要的话,对registerSubtypes(...)的调用可以放在不同的方法中。

相关问题