Home > Back-end >  Spring Boot Rest Controller: Return Collection<? extends SomeClass>
Spring Boot Rest Controller: Return Collection<? extends SomeClass>

Time:05-18

I have an abstract class in my application called Annotation containing only a single enum field representing the Annotation type. I have two classes, LinkAnnotation and TextAnnotation, which extend Annotation. Both are simple classes with a few String fields representing the slightly different needs for each type of annotation in some text.

I have a class called AnnotatedString which has the following structure:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class AnnotatedString {
    private String rawContent;
    private Boolean hasAnnotations;
    private Set<?> annotations = new HashSet<>();
}

I have attempted to configure the annotations field as the following:

private Set<Annotation> annotations = new HashSet<>();
private Set<? extends Annotation> annotations = new HashSet<>();
private Set<?> annotations = new HashSet<>();

But in each case when I return the object containing the AnnotatedString from my RestController GetMapping method I am only seeing the type field from the abstract Annotation class in the JSON and none of the fields from the child classes. What I would like to see in my JSON is an array of JSON objects with the fields corresponding to the Java type that the Set actually contains. Is this possible with Spring Boot, and if so how would I go about setting it up?

CodePudding user response:

As pointed by Brendon Dugan in his comment, adding the JsonTypeInfo annotation over the parent class with the use attribute equal to JsonTypeInfo.Id.MINIMAL_CLASS ensures that the Java class name with minimal path will be used as the type identifier for subclasses of the parent class. As a consequence the right subclass type will be added to all objects included in the Set collection, solving the issue.

  • Related