json - Kotlinx序列化解析枚举忽略未知值
问题描述
我有一个看起来像这样的 json:
[
{
"object": [
{
"enumValue1": "value1",
"value2": 1
}
],
},
{
"object2": [
{
"enumValue1": "value2",
"value2": 2
}
],
},
{
"object3": [
{
"enumValue1": "value1",
"value2": 3
}
],
},
{
"object4": [
{
"enumValue1": "unknown",
"value2": 4
}
],
},
]
我想用 kotlinx 序列化解析这个 json 我已经创建了一个类和一个枚举:
@Serializable
data class Class {
@SerialName("enumValue1")
val enumValue1: EnumValue
@SerialName("value2")
val value2: Int
}
@Serializable
enum class EnumValue {
@SerialName("value1") VALUE_1,
@SerialName("value2") VALUE_2
}
我希望解析的输出是一个列表,其中包含 3 个对象(未解析值为“未知”的对象)
我怎样才能实现它?我尝试过:
ignoreUnknownKeys = true
coerceInputValues = true
但它不起作用:
Field 'enumValue1' is required for type with serial name, but it was missing
谢谢你的帮助
解决方案
您应该将 enumValue1 声明为可为空:
val enumValue1: EnumValue?
这将使它成为可选的。
推荐阅读
- javascript - 如果特定月份显示内容
- lwc - 闪电进度指示器图标
- kotlin - 如何从 RoundEnvironment 为自定义注释处理器获取正确的 kotlin 类型?
- javascript - Swiper 无法正确捕捉到下一张幻灯片
- facebook-graph-api - 为什么在生成系统用户令牌时禁用 commerce_* 权限?
- vb.net - 从字典值切换的动态生成的按钮不会切换
- javascript - 智能合约不通过网站调用
- tensorflow - 量化目标检测模型
- asp.net - 反序列化没有根对象和 1 个数组 ASP.NET MVC 的 json
- google-cloud-platform - 从 GCS 环境中的平面文件加载 Hive 外部表失败