Support for deserializing JSON string values as enums in a sealed type hierarchy #6184
runeflobakk
started this conversation in
Ideas
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
I have been playing a bit with the combination of a sealed interface, annotated with
@JsonTypeInfo(use = JsonTypeInfo.Id.DEDUCTION), and some permitted subclasses. I find this feature very nice, with the caveat that the existence of attributes in the JSON must uniquely identify type.I was wondering if it would make sense to support enums as permitted subtypes of a sealed interface, and using
Id.DEDUCTION?Given e.g. a hierarchy like this:
I can, as expected, deserialize
MyObjectand get theBasefield mapped as eitherAorBrecords automatically. But I think it would be really nice if it was also possible to support JSON string values to be deserialized as a matching enum constant, e.g. to sort of include the standard enum deserializing-support into the support forJsonTypeInfo.Id.DEDUCTIONon a sealed interface.Expressed as a test:
I think the sort of equivalent caveat can apply here as the mentioned "existence of attributes in the JSON must uniquely identify type" for beans/records, i.e. if there are multiple permitted enum subtypes of the sealed interface, as long as the names are unique across all the enums, it is possible to resolve which enum constant to resolve from a JSON string.
I did some tinkering with a custom deserializer, to see if I could inspect
JsonParser.hasToken(JsonToken.VALUE_STRING), and in that case delegate to deserializing an enum constant, and otherwise do the regular resolving of the record/bean to deserialize, but this proved to be a too difficult task for me to tap into the existing "plumbing" in Jackson instead of doing my own frail reimplementation of the deserialization facilities already present.What do you think? :)
All reactions