https://kotlinlang.org logo
t

tim

05/15/2020, 12:39 PM
Is there a way to globally specify a deserialiser for a specific type with Kotlin + Jackson? My use case: I get a Timestamp { second:Long, nano: Int } back from Firestore, and I want to de-serialise it to a Long inside my application. I have several data classes expecting a Long (created/updated properties) and so I'd like to centralised this logic so that whenever a Timestamp is deseriliased my customer deserialiser is called. I'd like to avoid annotating every Long-from-Timestamp data class property with
@JsonDeserialize(using = FirestoreTimestampDeserializer::class)
if possible?
d

diesieben07

05/15/2020, 12:53 PM
I think you should be able to register a custom serializer globally using a module: https://github.com/FasterXML/jackson-docs/wiki/JacksonHowToCustomSerializers#with-jackson-17-and-above
t

tim

05/15/2020, 1:01 PM
ahh perfect will give this a try ty!
Hmm it looks like globally registering a deserialiser for Long isn't going to work in my case, because obviously Long is a primitive used in other cases (ie. saved/restored as a Long), and in one specific case of mine saved/restored to and from a Timestamp. I guess I'd have to wrap my Long into a custom type to achieve what I want
d

diesieben07

05/15/2020, 1:56 PM
Hm. Stackoverflow suggests that it works just fine: https://stackoverflow.com/a/25945058
How did you register it?
t

tim

05/15/2020, 2:01 PM
I'm pretty sure its working as its suppose to I think the flaw is in my design ... I'm treating Long differently in different situations. In some situations I want Longs to be deserialised with my custom deserialiser, and in others I want them to be deserialised directly. I could expand the logic inside my deserialiser to handle both instances (where its restoring from a Timestamp and the other instance where its restoring from a number) but I think a better design is to wrap my long-based timestamp as a ValueObject and only put custom serialisation logic against that?
d

diesieben07

05/15/2020, 2:02 PM
You could do that, yes.
t

tim

05/15/2020, 2:02 PM
Or perhaps thats not any better?
d

diesieben07

05/15/2020, 2:02 PM
A richer type system is often desirable, yes.
t

tim

05/15/2020, 2:02 PM
but the code you directed me does work 🙏 its just an error in my design 🙂
d

diesieben07

05/15/2020, 2:02 PM
If you are on the JVM anyways, why not use Java 8 types, like
Instant
?
☝🏻 1
t

tim

05/15/2020, 2:04 PM
ya i should 😳
8 Views