Using Java 17 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 Set Jackson JSON serialization for specific type to use toString() using ObjectMapper that I can specify a ToStringSerializer as a serializer in a Module, as the answer indicated:
…
module.addSerializer(Bar.class, new ToStringSerializer());
//technically ToStringSerializer.instance would be better, but it's the same idea
…
But now how about deserializing Bar using a static factory method? Without further context Jackson won't know the type of the string, but if it's deserializing a property of Foo e.g. Foo.bar, it will know the type should be Bar. So is there a way to set up a deserializer that will use a static factory method Bar.createNewBarInstance to create a Bar when setting Foo.bar? Something like this?
…
module.addDeserializer(Bar.class,
new StaticFactoryDeserializer("createNewBarInstance"));
…
Is there some sort of deserializer for static factory methods that gives me that sort of functionality?
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). Does that mean there is nothing that would allow new StaticFactoryDeserializer("forName") and new StaticFactoryDeserializer("create"), etc. to do the same thing? Surely someone has thought of this before.
StaticFactoryDeserializer, where I indicate a static factory method such ascreateNewBarInstance. Is there such a deserializer implementation already? Or are you saying I have to write one?Bartype? But there are so many classes that need that—why create the same boilerplate over and over, if the only difference is knowing the name of the static factory method?Function<String, T>. Then instantiate it once per each class likeaddDeserializer(Bar.class, new CustomDeserializer<Bar>(SomeClass::stringToBarFunction));. Hope i've described well enough.