0

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?

H.Step
  • 95
  • 1
  • 10
  • `when the backend returns null I get an Exception:` Well you only will get a NullPointerException if you use that returned null. So check for null before use i would say. Please post the code that tries to use that null. – blackapps Oct 25 '21 at 10:57
  • `when the backend returns null` ? What kind of backend is that? A https server? I wonder what you have in mind if you say that a server returns [] or null. – blackapps Oct 25 '21 at 11:02

1 Answers1

2

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.

Aleksei Tirman
  • 4,658
  • 1
  • 5
  • 24
  • Was using this workaround, but wondering may be there's another way. Anyway your answer cleared my doubts, thanks! – H.Step Oct 26 '21 at 06:55