Skip to content

Custom static factory-based deserializer? #4004

Open
@garretwilson

Description

@garretwilson

As I noted on Stack Overflow, I'm using Java 17 and I have a Bar type I want serialized to JSON using its toString() method. I'm serializing using a Jackson ObjectMapper (created via a JsonMapper.Builder). I found out from my other Stack Overflow question that I can specify a ToStringSerializer as a serializer in a Module, as the answer indicated. (I had done this years ago, but forgotten how.)

module.addSerializer(Bar.class, new ToStringSerializer());
//technically ToStringSerializer.instance would be better; I used instantiation for

But now how about deserializing Bar using a static factory method? Looking at the code from FromStringDeserializer.Std._deserialize(…), I see that known types are simply checked using a case and then the static factory methods are explicitly invoked, e.g. Charset.forName(value) or URI.create(value). This indicates to me that there may not be an existing deserializer for general serializer types—otherwise we could just use new StaticFactoryDeserializer("forName") and new StaticFactoryDeserializer("create"), etc. to do the same thing.

Of course I can write one of these myself, but I'm curious whether this exists already. Basically I'd like to do this:

module.addDeserializer(Bar.class, new StaticFactoryDeserializer("createNewBarInstance"));
…

StaticFactoryDeserializer would also allow a Function, so I could use it like this:

module.addDeserializer(Bar.class, new StaticFactoryDeserializer(Bar::createNewBarInstance));
…

(Probably the deserializer would create its own function instance internally when created with the method name, but that's an implementation detail.)

Does such a deserializer exist, or is one planned? If I wrote one, would it be something you'd be interested in including in Jackson?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions