我正在使用 Ktor 将 Moshi 序列化转换为 kotlinx 序列化,当我尝试请求获取数据时出现此错误
kotlinx.serialization.MissingFieldException:字段“附件”是必需的,但缺少
这是有道理的,因为这个特定的响应不包含这个字段
响应 JSON
{
"data": {
"id": "1299418846990921728",
"text": "This is a test"
}
}
但是我的序列化类的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)
}
}
为什么即使它可以为空,它仍然说该字段是必需的?