首页 > 解决方案 > 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

谢谢你的帮助

标签: jsonkotlinx.serialization

解决方案


您应该将 enumValue1 声明为可为空:

val enumValue1: EnumValue?

这将使它成为可选的。


推荐阅读