【发布时间】:2021-12-10 20:09:42
【问题描述】:
我使用 Ktor 获取这样的列表,在某些情况下返回 null。
override suspend fun getDevices(accessToken: String): List<Device>? {
return client.get {
url(path = "/devices")
header("Authorization", "Bearer $accessToken")
}
}
但是,当后端返回 null 时,我得到一个异常:
W/System.err: java.lang.NullPointerException
W/System.err: at io.ktor.client.features.json.serializer.KotlinxSerializer.read(KotlinxSerializer.kt:37)
这里最好的方法是什么?我认为最简单的方法是调整后端返回 [] 而不是 null,但是可以在客户端解决吗?或者是否有一个普遍的协议是后端应该返回 [] 而不是 null?
【问题讨论】:
-
when the backend returns null I get an Exception:好吧,如果你使用返回的 null,你只会得到一个 NullPointerException。所以我会说在使用前检查null。请发布尝试使用该 null 的代码。 -
when the backend returns null?那是什么样的后端? https服务器?如果您说服务器返回 [] 或 null,我想知道您的想法是什么。
标签: android kotlin ktor kotlinx.serialization