Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error "null cannot be cast to non-null type kotlin.Any" decoding invalid json #334

Open
mamcx opened this issue May 18, 2021 · 0 comments
Open

Comments

@mamcx
Copy link

mamcx commented May 18, 2021

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"}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant