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
spand
03/24/2020, 12:59 PM
Tried setting the id type to
Any
and just store a String or Int in it?
m
madhead
03/24/2020, 1:04 PM
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
madhead
03/24/2020, 1:04 PM
I’m thinking about a sealed class, like
Either
+ custom serializer
s
spand
03/24/2020, 1:12 PM
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
madhead
03/24/2020, 1:16 PM
I don’t know, but I guess yes. String ids are like usernames: