我有一个带有 REST API 的 Kotlin 应用程序。
POST
端点接受请求正文,该请求正文被反序列化到此数据类中:
data class RequestBody(
val ids: Ids? = null,
)
data class Ids(
val include: List<String>? = null,
val exclude: List<String>? = null
)
使用以下方式调用此端点时:
{
"ids": {
"include": [
null
]
},
}
尝试使用 kotlinx JSON 序列化程序序列化 RequestBody 时,出现 NPE:
val jsonSerializer = Json { encodeDefaults = true }
fun getData(
ids: Ids
): Output {
val inputJson = jsonSerializer.encodeToJsonElement(
ids = Ids ?: Ids()
)
...
}
错误信息:
java.lang.NullPointerException: Parameter specified as non-null is null: method kotlinx.serialization.internal.StringSerializer.serialize
对我来说,问题似乎出在请求正文的反序列化期间,因为,例如,如果我将
Ids
设置为不可空:val ids: Ids
,然后尝试使用 "ids": null
调用端点,那么我会得到预期的错误:JSON parse error: Instantiation of [...] value failed for JSON property ids due to missing (therefore NULL) value for creator parameter ids which is a non-nullable type
。
那么,为什么当我在 include
列表中传递 null 时,即使 String
类型被指定为不可为空,它也不会抛出此错误?
编辑:在Kotlin文档中,它说Kotlin中NPE的唯一可能原因是:
这看起来不适合其中任何一个?
是的,您正在将
null
值传递到不接受 null
的列表中。尝试发布这个:
{
"ids": {
"include": null
},
}
或者,更新列表以接受
null
值:
val include: List<String?>? = null