Java ExternalTypeHandler-class And Method Code Example


Here is an example of using the ExternalTypeHandler class from the com.fasterxml.jackson.databind package in the Jackson library to handle external types:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.ExternalTypeHandler;
import com.fasterxml.jackson.databind.jsontype.TypeIdResolver;

public class ExternalTypeHandlerExample {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        ExternalTypeHandler extHandler = new ExternalTypeHandler(new MyTypeIdResolver());
        mapper.registerModule(extHandler);

        MyObject obj = new MyObject();
        obj.setType("myType");
        obj.setValue("myValue");

        String json = mapper.writeValueAsString(obj);
        System.out.println(json);

        MyObject obj2 = mapper.readValue(json, MyObject.class);
        System.out.println(obj2.getType());
        System.out.println(obj2.getValue());
    }
}

class MyObject {
    private String type;
    private String value;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}

class MyTypeIdResolver implements TypeIdResolver {
    @Override
    public String idFromValue(Object value) {
        return ((MyObject) value).getType();
    }

    @Override
    public String idFromValueAndType(Object value, Class<?> suggestedType) {
        return ((MyObject) value).getType();
    }

    @Override
    public void init(JavaType bt) {
    }

    @Override
    public JavaType typeFromId(DatabindContext context, String id) {
        return context.constructType(MyObject.class);
    }

    @Override
    public String getDescForKnownTypeIds() {
        return null;
    }
}

This code defines a simple MyObject class with type and value properties, as well as a MyTypeIdResolver class that implements the TypeIdResolver interface. The ExternalTypeHandler is then registered with an ObjectMapper and used to serialize and deserialize MyObject instances.

The MyTypeIdResolver defines the logic for external type resolution. The ExternalTypeHandler is used to handle the resolution of the external type.