0

I've a json which looks like:

[
  {
    "object": [
      {
        "enumValue1": "value1",
        "value2": 1
       }
    ],
  },
  {
    "object2": [
      {
        "enumValue1": "value2",
        "value2": 2
       }
    ],
  },
  {
    "object3": [
      {
        "enumValue1": "value1",
        "value2": 3
       }
    ],
  },
  {
    "object4": [
      {
        "enumValue1": "unknown",
        "value2": 4
       }
    ],
  },
]

I want to parse this json with kotlinx serialization I've created a class and an enum:

@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
}

I expect the output of the parsing to be a list, with 3 objects in (object with value "unknown" not parsed)

How could I achieve it? I have try:

ignoreUnknownKeys = true
coerceInputValues = true

But it doesn' work:

Field 'enumValue1' is required for type with serial name, but it was missing

Thanks for your help

JohnDoe
  • 1
  • 2
  • You may need to declare enumValue1 as nullable, like this: – Ravi Wallau Oct 20 '21 at 13:13
  • (1) You don't show the code where serialization happens. What are you trying to serialize? (It should be `List`) (2) Which instances do you expect to get in your list? Clearly they cannot be instances of `Class`, since it contains `EnumValue` which can't be "unknown". This hints at a different question/solution than what you are asking for. – Steven Jeuris Dec 08 '21 at 17:00

1 Answers1

0

You should declare enumValue1 as nullable:

val enumValue1: EnumValue?

That will make it optional.

Ravi Wallau
  • 10,416
  • 2
  • 25
  • 34