我的应用程序中有一个名为 Annotation 的 abstract class ,其中仅包含一个表示 Annotation 类型的枚举字段。我有两个类,LinkAnnotation 和 TextAnnotation,它们扩展了 Annotation。两者都是简单的类,带有一些字符串字段,表示某些文本中每种注释类型的需求略有不同。
我有一个名为 AnnotatedString 的类,它具有以下结构:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AnnotatedString {
private String rawContent;
private Boolean hasAnnotations;
private Set<?> annotations = new HashSet<>();
}
我试图将注释字段配置如下:
private Set<Annotation> annotations = new HashSet<>();
private Set<? extends Annotation> annotations = new HashSet<>();
private Set<?> annotations = new HashSet<>();
但是在每种情况下,当我从我的 RestController GetMapping 方法返回包含 AnnotatedString 的对象时,我只看到 JSON 中抽象 Annotation 类的类型字段,而没有看到子类中的任何字段。我希望在我的 JSON 中看到一个 JSON 对象数组,其中的字段对应于 Set 实际包含的 Java 类型。 Spring Boot 是否可以做到这一点,如果可以,我将如何进行设置?
回答1
正如 https://stackoverflow.com/users/873043/brendon-dugan 在他的评论中指出的那样,在父类上添加 https://fasterxml.github.io/jackson-annotations/javadoc/2.12/com/fasterxml/jackson/annotation/JsonTypeInfo.html 注释,其 use
属性等于 https://fasterxml.github.io/jackson-annotations/javadoc/2.12/com/fasterxml/jackson/annotation/JsonTypeInfo.Id.html#MINIMAL_CLASS 确保具有最小路径的 Java 类名将用作父类的子类的类型标识符。因此,正确的子类类型将添加到 Set
集合中包含的所有对象中,从而解决了该问题。