Dynamic @JsonSubTypes When Parsing Java JSON

Viewed 249

I have a system that involves dynamic @JsonSubTypes contributors and I'm trying to figure out how to refactor my code (example below) to not use the @JsonSubTypes annotation but instead provide these values dynamically or in runtime. Does anyone know if this is possible?

   @JsonSubTypes({
    @JsonSubTypes.Type(value = Dog.class, name = "dog"),
    @JsonSubTypes.Type(value = Cat.class, name = "cat")
})
1 Answers

Researched this and there are a couple of different approaches that can be taken, the one that made the most sense is declaring this annotation on a base class that will have different sub class implementations.

@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")

This will add a "@class" meta field into the serialized JSON that is then used when deserializing to determine what subclass is being used. Only down side is having to include the field when composing manual JSON.

Related