You are currently viewing Best way to handle numbers as keys in a nested json-like classes file with kotlinx

Best way to handle numbers as keys in a nested json-like classes file with kotlinx


I am trying to serialize the content of a json string that can take the following format:

-888888: { "lat": 8.2, "lon": -90.3, "schedule": { "friday": [ { "date_arr": "friday", "remarks": " OK", "time_arr": "07:10", "time_dep": "06:40", "trans_name": "C" } ] }

However I am struggling with my current serializable class implementation. The top key (-723232569) will vary, it will be generated randomly from one iteration to another. I would like to extract they key and its value with the following class implementation.

u/Serializable data class TimeSlot(val date_arr: String, val remarks: String, val time_arr: String, val time_dep: String, val trans_link: String, val trans_name: String, val trans_tel: String, val to_lat: String? = null, val to_lon: String? = null) u/Serializable data class Schedule(val monday: List<TimeSlot>, val tuesday: List<TimeSlot>, val wednesday: List<TimeSlot>, val thursday: List<TimeSlot>, val friday: List<TimeSlot>, val saturday: List<TimeSlot>, val sunday: List<TimeSlot>) u/Serializable data class Stop(val lat: Double, val lon: Double, val schedule: Schedule)

However when executing the following code

 try { val neww = """{ "-888888": { "lat": 8.753437, "lon": -82.943344, "schedule": { "friday": [ { "date_arr": "friday", "remarks": " OK", "time_arr": "07:10", "time_dep": "06:40", "trans_name": "C" }]}}}""" val res = format.decodeFromString<Stop>(neww) } catch (ioException: IOException) { ioException.printStackTrace() }

I am encountering

Unexpected JSON token at offset 27: Encountered an unknown key '-888888'. Use 'ignoreUnknownKeys = true' in 'Json {}' builder to ignore unknown keys.

Any idea how I could parse this kind of data ? Ideally id like to have everything in a class, but if I need to get some bits of it as a map structure it could also be fine



Error and code

submitted by /u/shtworld
[link] [comments]