Spring 引导休息控制器:Return 集合<?扩展某些类>

Spring Boot Rest Controller: Return Collection<? extends SomeClass>

我的应用程序中有一个名为 Annotation 的抽象 class,它仅包含一个代表 Annotation 类型的枚举字段。我有两个 classes,LinkAnnotation 和 TextAnnotation,它们扩展了 Annotation。两者都是简单的 classes,带有几个 String 字段,代表某些文本中每种注释类型略有不同的需求。

我有一个名为 AnnotatedString 的 class,它具有以下结构:

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

但是在每种情况下,当我 return 包含来自我的 RestController GetMapping 方法的 AnnotatedString 的对象时,我只看到来自 JSON 中的抽象注释 class 的类型字段,并且none 来自子 class 的字段。我希望在 JSON 中看到的是一个 JSON 对象数组,其字段对应于 Set 实际包含的 Java 类型。 Spring Boot 是否可行,如果可以,我将如何设置它?

正如 Brendon Dugan in his comment, adding the JsonTypeInfo annotation over the parent class with the use attribute equal to JsonTypeInfo.Id.MINIMAL_CLASS 所指出的,确保具有最小路径的 Java class 名称将用作父 [=] 的子 class 的类型标识符18=]。因此,正确的 subclass 类型将添加到 Set 集合中包含的所有对象,从而解决问题。