Java BasicPolymorphicTypeValidator-class And Method Code Example


Here is an example of how to use the BasicPolymorphicTypeValidator class in the com.fasterxml.jackson.databind package to validate a JSON object that contains a field with a polymorphic type:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.cfg.MapperConfig;
import com.fasterxml.jackson.databind.jsontype.PolymorphicTypeValidator;

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

        ObjectMapper mapper = new ObjectMapper();

        // Create a basic polymorphic type validator
        PolymorphicTypeValidator ptv = BasicPolymorphicTypeValidator.builder()
                                            .allowIfSubType(Animal.class)
                                            .build();
        mapper.activateDefaultTyping(ptv);
        // deserialize JSON
        Animal animal = mapper.readValue(json, Animal.class);

        // Use the deserialized object
        System.out.println(animal);
    }
}

abstract class Animal {
    protected String name;
    public Animal(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
}
class Dog extends Animal {
    private boolean bark;
    public Dog(String name, boolean bark) {
        super(name);
        this.bark = bark;
    }
    public boolean isBark() {
        return bark;
    }
}
class Cat extends Animal {
    private boolean meow;
    public Cat(String name, boolean meow) {
        super(name);
        this.meow = meow;
    }
    public boolean isMeow() {
        return meow;
    }
}
class Animals {
}

In this example, an instance of the ObjectMapper class is used to deserialize a JSON string into an instance of the Animal class. The activateDefaultTyping() method is used to enable default typing, and the BasicPolymorphicTypeValidator.builder().allowIfSubType(Animals.class).build() is used to create an instance of the BasicPolymorphicTypeValidator class that only allows subtypes of Animals.

The basic polymorphic type validator only allows the type if it is a subtype of the specified base class. In this case, only subtypes of Animals class are allowed. In the JSON example, the Dog class is a subtype of the Animals class, so the deserialization will work fine.

It's important to notice that this is a basic example and you may need to configure the validator according to your specific needs, for example, you can use allowIfBaseType() method to allow only the specified base type, or you can use disallow() method to disallow any type.