I have a sealed class `Event<P>`, and a bunc...
# announcements
a
I have a sealed class
Event<P>
, and a bunch of objects that inherit from the class with a few different types for
P
. I receive some json that has a name field so that I can match it to one of the objects, and data field that I want to deserialize into an object of type
P
. Is there any way to do this without doing a case-by-case when for each event type?
j
What are you using for JSON serialization? I know that Jackson has capabilities for doing this.
a
I am using gson but I don't really mind switching to jackson
kotlinx.serialization
also supports polymorphism. (Although combining it with generics is a bit.... complicated)
j
Take a look at the docs for
@JsonTypeInfo
inside Jackson. There are a few ways to wire it in, but I've never used it with Generics.
Basically you'll want to annotate your Event class and then register the subtypes on your ObjectMapper (which is the main class for Jackson)
a
Moshi is also a good choice if you're already using gson, it has a kotlin code generator to avoid reflection as well
n
@jw: We are internally converging on Jackson (and thus away from Gson among others), but is this "never use Gson" really an official (and quotable) statement from the Gson project? If yes, I might have arguments for accelerating that convergence.
j
You'll get that statement from 2/3 maintainers. Is simple majority good enough?
n
Sure. An Moshi or Jackson are recommended replacements?
j
Or kotlinx.serialization
n
Yeah. However, we also use YAML a lot and no multi-platform yet and still have legacy Java code and thus Jackson currently is the front-runner