Java FactoryBasedEnumDeserializer-class And Method Code Example


import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer;
import com.fasterxml.jackson.databind.util.EnumResolver;

import java.io.IOException;

public class FactoryBasedEnumDeserializer<T extends Enum<T>> extends StdScalarDeserializer<T> {
    private EnumResolver<T> _resolver;

    public FactoryBasedEnumDeserializer(EnumResolver<T> resolver) {
        super(resolver.getEnumClass());
        _resolver = resolver;
    }

    @Override
    public T deserialize(JsonParser parser, DeserializationContext context) throws IOException {
        String value = parser.getValueAsString();
        return _resolver.findEnum(value);
    }
}

This is an example of a custom deserializer for an Enum type in Jackson. This class extends StdScalarDeserializer and overrides the deserialize method to handle converting a JSON value to an Enum instance.

It uses EnumResolver to find the Enum based on the json value, it takes the EnumResolver in constructor and uses it to deserialize the Enum.

It is called FactoryBasedEnumDeserializer because it uses EnumResolver which is a factory for Enum.

You will need to use this deserializer along with ObjectMapper.registerModule() method to register this deserializer to be used by the ObjectMapper.