2

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());
0

1 Answer 1

5

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Ah, that's it! It's coming back to me now—I had forgotten I needed to put that in a module. Thanks for taking the time to post this.
I added follow-up question stackoverflow.com/q/76560273 .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.