m

    madhead

    2 years ago
    Hello! I want to use a third-party API that expects either int or string as a value for id. Like:
    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

    2 years ago
    Tried setting the id type to
    Any
    and just store a String or Int in it?
    m

    madhead

    2 years ago
    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

    spand

    2 years ago
    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

    2 years ago
    I don’t know, but I guess yes. String ids are like usernames:
    @user
    Edward Taylor

    Edward Taylor

    2 years ago
    m

    madhead

    2 years ago
    Thank you, Edward! That’s it!