Thread
#serialization
    b

    bissell

    4 years ago
    Does anyone know a way to parse a JSON field which could contain either a String or a Number to
    String
    or
    Long
    in Kotlin? My first thought was to attempt to read the field as a Number, and then if that fails (presumably because the field is another JSON type), then try to read it as String. But I haven't been able to write a method that can do this.
    gildor

    gildor

    4 years ago
    Looks like a bad API design. I think the only good solution is always parse as String
    b

    bissell

    4 years ago
    I agree it's not the greatest schema for an API, but unfortunately it's part of the JSON-RPC spec.
    The
    id
    field sent by a client may have a String, a Number, or null, and the server is meant to always return exactly the same value in the response
    gildor

    gildor

    4 years ago
    Oh, I see. Maybe just use different models, one for input with string id and two for output, int and string versions. Probably not the perfect, bit at least can be handled without custom parser.
    b

    bissell

    4 years ago
    Well then I'm right back where I started. If the server parses all input to a string then it loses the information needed to write the
    id
    back out, and doesn't know whether to write
    5
    or
    "5"
    gildor

    gildor

    4 years ago
    I see, it’s really unfortunate. I tried to play little bit with custom serializers, but looks on level of serializer for specific class you still cannot distingue between string and int, just because you have no access on this level to such low level. Maybe in you case make sense to just copy
    JSON
    parser implementation and add support of such parsing. Maybe there are some other solutions, but I don’t see them without change API of kotlinx.serialization. Anyway, maybe make sense to create an issue with you case on kotlinx.serialization tracker