Is it possible to define a deserializer for a clas...
# serialization
m
Is it possible to define a deserializer for a class that can deserialize from 2 different unambiguous formats? Example:
Copy code
{ "createdAt": 11112222333 }
{ "createdAt": { "seconds": 179879, "nanoseconds": 1201800000 } }
Copy code
class DateTime(....)

@Serializable
class Payload(val createdAt: DateTime)
(serialization is not needed)
d
Yes this is possible. Just deserialise to JsonElement and do the rest yourself.
m
ah, that makes sense
let me give that a go
d
Depending on what DateTime looks like, you may be able to get kotlinx-serialisation to do more of the work for you.
m
it has a
val milliseconds: Long
in it
I intend to truncate the nanosecond precision I get from the json
d
Ah fairs. You'll have to DIY then. I was going to suggest surrogate types.
m
is there a better way to do this detail?
d
I though you didn't want to serialize?
m
I don't but I have to implement both methods of the
KSerializer
interface, no?
d
Nope, just the one you need.
You can leave that one as is,.
m
🤔
d
Don't remove the method lol, just leave it with the exception,.
m
ah okay, that's what I meant if there was a better way of doing it besides the exception 😄
d
Ahhh I see. Maybe `TODO()`` but 🤷🏼 .
m
yeah, TODO implies it will be implemented, I guess this conveys more of a "I won't do it"
d
Did you succeed?
m
I did, tho I'm a bit sad that I can't at compile time guarantee that there are no attempts to serialize
DateTime
d
Ah yeah, can understand that.
a
Isn't there also a DeserializationStrategy interface? I think KSerializer just implements DeserializationStrategy and SerializationStrategy
d
Yes but it has limited use cases, this is not one of them. The
@Serializable
needs the full
KSerializer
interface.