https://kotlinlang.org logo
b

bissell

05/26/2018, 7:54 PM
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.
g

gildor

05/27/2018, 7:23 AM
Looks like a bad API design. I think the only good solution is always parse as String
b

bissell

05/27/2018, 2:46 PM
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
g

gildor

05/27/2018, 4:18 PM
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

05/27/2018, 10:08 PM
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"
g

gildor

05/28/2018, 3:11 AM
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
3 Views