我正在使用Ktor将Moshi转换为kotlinx serialization,但是当我尝试请求获取数据时出现此错误:
kotlinx.serialization.MissingFieldException: Field 'attachments' is required, but it was missing
这很有道理,因为特定的响应并不包含此字段。
响应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)
}
}
即使该字段可为空,为什么仍然显示该字段是必填的?