【发布时间】:2021-02-24 01:04:24
【问题描述】:
我正在使用 Ktor 从 Moshi 转换为 kotlinx 序列化,当我尝试请求获取数据时出现此错误
kotlinx.serialization.MissingFieldException: 字段“附件”是 必填,但没找到
这是有道理的,因为此特定响应不包含此字段
响应 Json
{
"data": {
"id": "1299418846990921728",
"text": "This is a test"
}
}
但是我的 Serialized 类的 attachments 字段可以为空(它仅在需要时才出现在响应中)所以它应该忽略它,我认为它与 Moshi 一样
@Serializable
data class ResponseData(
val id: Long
val attachments: Attachments?,
val author_id: String?,
val text: String
}
在我的 Ktor 客户端设置中,我将其设置为忽略未知键
private val _client: HttpClient = HttpClient(engine) {
install(JsonFeature) {
val json = Json {
this.isLenient = true
this.ignoreUnknownKeys = true
}
serializer = KotlinxSerializer(json)
}
}
为什么即使它可以为空,它仍然说该字段是必需的?
【问题讨论】:
标签: ktor kotlinx.serialization