Home > other >  NullPointerException at KotlinxSerializer when GET returns null instead of a List
NullPointerException at KotlinxSerializer when GET returns null instead of a List

Time:10-27

Using Ktor I'm fetching a List like this, which in some cases returns null.

override suspend fun getDevices(accessToken: String): List<Device>? {
    return client.get {
        url(path = "/devices")
        header("Authorization", "Bearer $accessToken")
    }
}

However, when the backend returns null I get an Exception:

W/System.err: java.lang.NullPointerException
W/System.err:     at io.ktor.client.features.json.serializer.KotlinxSerializer.read(KotlinxSerializer.kt:37)

What is the best approach here? I think the easiest would be to adjust the backend to return [] instead of null, but can it be solved on the client side? Or is there a general agreement that the backend should return [] instead of null?

CodePudding user response:

The problem is that any JsonSerializer in Ktor can deserialize JSON text only to a non-nullable object because of the read method signature:

fun read(type: TypeInfo, body: Input): Any

The NullPointerException is thrown because at the end of that method the !! operator is used for converting a value to a non-null type.

As a workaround, you can catch the NullPointerException and return null value. This behavior will be fixed in Ktor 2.0.0.

  • Related