klaxon
klaxon copied to clipboard
Error "null cannot be cast to non-null type kotlin.Any" decoding invalid json
I trying to decode some JSON with com.beust:klaxon:5.5
and bail out If I get something invalid, however in Klaxon().parse
I don't get a null but a inner exception:
Caused by: java.lang.NullPointerException: null cannot be cast to non-null type kotlin.Any at com.beust.klaxon.JsonObjectConverter.calculatePolymorphicClass(JsonObjectConverter.kt:233) at com.beust.klaxon.JsonObjectConverter.initIntoUserClass(JsonObjectConverter.kt:55) at com.beust.klaxon.JsonObjectConverter.fromJson(JsonObjectConverter.kt:30) at com.beust.klaxon.DefaultConverter.fromJsonObject(DefaultConverter.kt:223) at com.beust.klaxon.DefaultConverter.fromJson(DefaultConverter.kt:40) at com.beust.klaxon.Klaxon.fromJsonObject(Klaxon.kt:296)
The code for trigger this:
data class Coordinates(val lat: Double, val long: Double)
data class JsonError(val kind: String, val message: String)
@TypeFor(field = "type", adapter = QueryTypeAdapter::class)
open class Query(val type: QueryType)
data class StartTravel(val from:Coordinates, val to:Coordinates): Query(QueryType.StartTravel)
data class Fail(val error:JsonError): Query(QueryType.Fail)
class QueryTypeAdapter: TypeAdapter<Query> {
override fun classFor(type: Any): KClass<out Query> = when(type as QueryType) {
QueryType.StartTravel-> StartTravel::class
QueryType.Fail -> Fail::class
}
}
private fun decode(json:String):Query {
val obj = Klaxon().parse<Query>(json) <--- HERE
obj ?: return Fail(
JsonError(
kind = "Json",
message = "Invalid JSON:$json"
))
return obj
}
and the invalid json:
{"Fail":{"kind":"JSON","message":"unknown variant `from`, expected one of `StartTravel`, `SearchingDriver`, `Fail` at line 1 column 7"}}