Hello! I want to use a third-party API that expec...
# serialization
m
Hello! I want to use a third-party API that expects either int or string as a value for id. Like:
Copy code
Request {
    id: int | string,
    name: string,
    // other fields
}
How do I do that with kotlinx.serialization? I only need to serialize my classes to JSON, no deserialization.
s
Tried setting the id type to
Any
and just store a String or Int in it?
m
No, because: 1. I want more type-safety 2. Serializer has not been found for type ‘Any’. To use context serializer as fallback, explicitly annotate type or property with @ContextualSerialization
I’m thinking about a sealed class, like
Either
+ custom serializer
s
Ok. Last guess I will bother you with. Does the api actually distinguish between int and string ? Or will it simply accept both… ie. is id=42 equivalent to id=“42”
m
I don’t know, but I guess yes. String ids are like usernames:
@user
e
m
Thank you, Edward! That’s it!