jackson-databind icon indicating copy to clipboard operation
jackson-databind copied to clipboard

possibility to not require JsonTypeInfo annotation for sealed classes?

Open pjfanning opened this issue 1 year ago • 3 comments

Scala, Kotlin and Java 17 have sealed classes. It is possible to write introspectors that find the subtypes. It would be great if jackson-databind could infer a default JsonTypeInfo setting for sealed traits/interfaces/abstract-classes

A default like this, perhaps:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
  • https://github.com/pjfanning/jackson-scala-reflect-extensions/pull/9
  • https://github.com/FasterXML/jackson-databind/pull/3549
  • https://kotlinlang.org/docs/sealed-classes.html

pjfanning avatar Sep 08 '22 21:09 pjfanning

Yes, I agree. See #3549 for related work.

I do think this probably needs to be somehow opt-in since there are probably some security concerns (I can't think of specifics but this tingles my spider sense wrt past experiences). Just a simple MapperFeature or something.

cowtowncoder avatar Sep 09 '22 16:09 cowtowncoder

@cowtowncoder a MapperFeature to enable a default JsonTypeInfo for sealed classes would be fine. Once enabled, any class that has subtypes would automatically support be deserialized as if it has the default JsonTypeInfo annotation on it.

pjfanning avatar Sep 09 '22 16:09 pjfanning

Right. Now that I think about this, however, I realize there is the big question of what @JsonTypeInfo defaults are. Or rather how to allow configuration -- a default like shown above is fine but there probably should be a way to customize it. Unfortunately we do not have JsonTypeInfo.Value type (unlike for some of annotations), although I guess one could be added. Specifying a class/interface with annotation could work I suppose.

Another thing to add to AnnotationIntrospector -- or, perhaps, this would be the main thing that exposes everything? -- would be a method to call to ask if given type is a "sealed type". This is where we have some options; one would be "yes/no/don't know" result, after which introspector (or something) would need to figure out @JsonTypeInfo parameterization. Another that it's this method that would actually return the parameterization.

Yet another is of course to instead bolt this in via existing handling of @JsonTypeInfo... but it seems cleaner to separate this out.

Regardless, modules (Kotlin, Scala, Java-17?) would provide their AnnotationIntrospectors to detect sealed types they know of and handle.

Does this sound good?

/cc @sigpwned apologies for your sealed class PR falling through the cracks -- but I think it might be possible to join forces here. The concept of sealed class is indeed a common shared concern.

cowtowncoder avatar Sep 09 '22 19:09 cowtowncoder