Search code examples
javajsonjacksonjackson-databind

Set Jackson JSON serialization for specific type to use toString() using ObjectMapper


Using Java 17 I have a FooBar type I want serialized to JSON using its toString() method. I'm serializing using a Jackson ObjectMapper (created via a JsonMapper.Builder).

I read that I can use the @JsonValue annotation on the FooBar class FooBar.toString() method. But is there a way to configure the ObjectMapper instead, without creating some special factory class specifically for FooBar? (I did this years ago but I don't remember if I created a separate factory implementation or what.)

I was expecting (hoping for) something like this:

objectMapperBuilder.serializerFor(FooBar.class, ToStringSerializer.instance());

Solution

  • Just use com.fasterxml.jackson.databind.ser.std.ToStringSerializer as a custom deserializer for the FooBar class:

    ObjectMapper mapper = new ObjectMapper();
    
    SimpleModule module = new SimpleModule();
    module.addSerializer(FooBar.class, new ToStringSerializer());
    mapper.registerModule(module);