Java JsonTypeIdResolver-class And Method Code Example


import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeIdResolver;
import com.fasterxml.jackson.databind.DatabindContext;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.jsontype.impl.TypeIdResolverBase;

@JsonTypeInfo(use = JsonTypeInfo.Id.CUSTOM, include = JsonTypeInfo.As.PROPERTY, property = "object_type")
@JsonTypeIdResolver(MyTypeIdResolver.class)
public abstract class MyObject {
    // class implementation
}

public class MyTypeIdResolver extends TypeIdResolverBase {

    @Override
    public String idFromValue(Object value) {
        return value.getClass().getSimpleName();
    }

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

    @Override
    public JavaType typeFromId(DatabindContext context, String id) {
        try {
            return context.constructType(Class.forName(id));
        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException(e);
        }
    }
}

This is an example of how to use the com.fasterxml.jackson.annotation.JsonTypeIdResolver annotation in Jackson. The @JsonTypeIdResolver annotation is used to specify a custom resolver class that should be used to handle type information when serializing and deserializing an object with polymorphic types.

In this example, the MyObject class is an abstract class, and the custom resolver class MyTypeIdResolver is used to handle the type information. The MyObject class is annotated with @JsonTypeInfo to indicate that the type information should be included in the JSON, using a property named object_type, and @JsonTypeIdResolver to indicate that the MyTypeIdResolver class should be used to handle the type information.

When serializing an instance of a subclass of MyObject, the resulting JSON will have an additional property object_type with the simple name of the class, and when deserializing JSON, the MyTypeIdResolver will be used to determine the class to instantiate based on the object_type value.

It's important to note that you can use different strategy for type identification, like JsonTypeInfo.Id.NAME, JsonTypeInfo.Id.CLASS or JsonTypeInfo.Id.MINIMAL_CLASS and the way of including the type identifier in the JSON, like JsonTypeInfo.As.PROPERTY, JsonTypeInfo.As.WRAPPER_OBJECT or JsonTypeInfo.As.WRAPPER_ARRAY