Java JsonSubTypes-class And Method Code Example


Here is an example of how to use the JsonSubTypes annotation from the Apache Commons IO library to handle polymorphic deserialization of JSON:

import org.apache.commons.io.output.JsonStringEncoder;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Example {

    @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
    @JsonSubTypes({
        @JsonSubTypes.Type(value = Dog.class, name = "dog"),
        @JsonSubTypes.Type(value = Cat.class, name = "cat"),
    })
    public static abstract class Animal {
        private String name;
        // getters and setters
    }

    public static class Dog extends Animal {
        private int barkVolume;
        // getters and setters
    }

    public static class Cat extends Animal {
        private int livesRemaining;
        // getters and setters
    }

    public static void main(String[] args) throws Exception {
        String json = "{\"type\":\"dog\",\"name\":\"Fido\",\"barkVolume\":5}";

        ObjectMapper mapper = new ObjectMapper();
        Animal animal = mapper.readValue(json, Animal.class);

        if (animal instanceof Dog) {
            Dog dog = (Dog) animal;
            System.out.println(dog.getName() + " barks at a volume of " + dog.getBarkVolume());
        }
    }
}

This will output:

Fido barks at a volume of 5

This example uses the JsonTypeInfo and JsonSubTypes annotations to specify that the type property in the JSON should be used to determine the actual type of the object when deserializing to a superclass (Animal) and that Dog and Cat are subtypes of Animal.

Note: This is using the Jackson JSON library to deserialize the JSON to POJO. You need to have the jackson-databind jar in your classpath for this to work.