Is it possible to encode/decode non-primitive types inside Mapper?
See original GitHub issueA project I am working on uses Google’s Firestore NoSQL database, and the Android SDK takes a Map<String, Any>
to create or update a record in the database.
The problem I’m working in is how to translate something like this:
data class Foo(val string: String, val number: Int, val timestamp: Instant)
into a map like this:
{
"string" to "whatever string value",
"number" to 1234,
"timestamp" to [corresponding instance of java.util.Date] // java.time.Instant instance translated to java.util.Date instance
}
Using encoders/decoders like the ones described here allow me to go straight from a data class to a map, which is great.
My problem is that I don’t know how to translate Instant
into a non-primitive. I can obviously write a custom Serializer for Instant like so
@Serializer(forClass = Instant::class)
object InstantSerializer : KSerializer<Instant> {
override val descriptor: SerialDescriptor =
StringDescriptor.withName("Instant")
override fun serialize(output: Encoder, obj: Instant) {
output.encodeString(obj.toString())
}
override fun deserialize(input: Decoder): Instant {
return Instant.parse(input.decodeString())
}
but then the map looks like
{
"string" to "whatever string value",
"number" to 1234,
"timestamp" to "2019-03-11T00:00:00Z"
}
Which would be great for sending a HTTP request or something along those lines. The problem is that if the Firestore SDK picks up a java.util.Date
in the Map<String,Any>
that you pass it when creating/updating an object, it will store it differently than if it is a String
representation of that time.
To sum it up, I’m wondering if it is possible to encode to/decode from an arbitrary, non-primitive type?
PS - I realize that timestamps in the ISO8601 format most likely can be sorted and queried against just as efficiently as any custom Date object that Firestore is using on their end, this is just the simplest example. There are others that would not work quite as well
Issue Analytics
- State:
- Created 5 years ago
- Comments:8 (4 by maintainers)
Top GitHub Comments
I think
currentTag
property is what you’re looking into.In case anyone else stumbles upon this, this is my final encoder class:
Thank you to @sandwwraith for all the help