Java JsonTypeId-class And Method Code Example


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

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

public class Example {

    public static abstract class Animal {
        @JsonTypeId
        protected String type;
        private String name;
        // getters and setters
    }

    public static class Dog extends Animal {
        public Dog() {
            this.type = "dog";
        }
        private int barkVolume;
        // getters and setters
    }

    public static class Cat extends Animal {
        public Cat() {
            this.type = "cat";
        }
        private int livesRemaining;
        // getters and setters
    }

    public static void main(String[] args) throws Exception {
        Dog dog = new Dog();
        dog.setName("Fido");
        dog.setBarkVolume(5);

        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(dog);
        System.out.println(json);
        Animal animal = mapper.readValue(json, Animal.class);
        if (animal instanceof Dog) {
            Dog deserializedDog = (Dog) animal;
            System.out.println(deserializedDog.getName() + " barks at a volume of " + deserializedDog.getBarkVolume());
        }
    }
}

This will output:

{"type":"dog","name":"Fido","barkVolume":5}
Fido barks at a volume of 5

This example uses the JsonTypeId annotation to specify that the type property in the JSON should be used to determine the actual type of the object when serializing and deserializing. The type variable is added to the abstract class and the value is set in the constructor of the subclasses.

Note: This is using the Jackson JSON library to handle polymorphic serialization and deserialization. You need to have the jackson-databind jar in your classpath for this to work.