Search code examples
javaserializationjacksonobjectmapper

Jackson ObjectMapper - How to configure to not use a custom Json Serializer


I am working on a project which has a custom JSON Serializer defined

public class JsonCustomSerializer extends JsonSerializer<CustomObject> {
    @Override
    public void serialize(
            CustomObject customObject,
            JsonGenerator jsonGenerator,
            SerializerProvider serializerProvider)
            throws IOException {
                // custom implementation
            }
}

I am using an ObjectMapper and invoking writeValueAsString(Object) method. This invokes the custom implementation as defined using the class JsonCustomSerializer. How can I configure ObjectMapper to not use the JsonCustomSerializer? The custom serializer is used by another instance of ObjectMapper in the application.


Solution

  • To configure ObjectMapper to ignore your custom serializer for a specific class, you can use the SimpleModule class provided by Jackson. Here's an example of how you can do this:

    
    public class Main {
        public static void main(String[] args) throws Exception {
            // Create ObjectMapper
            ObjectMapper objectMapper = new ObjectMapper();
    
            // Create a SimpleModule
            SimpleModule simpleModule = new SimpleModule();
    
            // Disable the custom serializer for CustomObject class
            simpleModule.addSerializer(CustomObject.class, new CustomObjectDefaultSerializer());
    
            // Register the module with the ObjectMapper
            objectMapper.registerModule(simpleModule);
    
            // Now, when you use this objectMapper, it won't use your custom serializer for CustomObject
    
            // Your code here...
        }
    }