Ignore a JSON key when it's the wrong type

I’m using json.decodeFromString() to deserialize some JSON.

My class looks like this:

@Serializable
data class IncomingMessage(
    val id: Int,
    val result: List<State>? = null
)

@Serializable
data class State(
    val entity_id: String,
    val state: String
)

I have enabled ignoreUnknownKeys.

Sometimes my JSON looks like this:

{
  "id": 3,
  "type": "result",
  "success": true,
  "result": [
    {
      "entity_id": "test",
      "state": "unknown",
      "last_changed": "2021-10-04T15:15:44.956070+00:00"
    },
    [...]
  ]
}

Then of course the deserialization works.

But sometimes it looks like this:

{
  "id": 5,
  "type": "result",
  "success": true,
  "result": {
    "context": {
      "parent_id": null,
    }
  }
}

In this case I’m not interested in result, but it breaks deserialization because it is not an array.

I don’t know beforehand which type of message I’m expecting, I have to actually look at the message to find out.

What’s the best way to solve this?

My workaround looks like this:

@Serializable
data class IncomingMessage(
    val id: Int,
    val result: JsonElement? = null
)

@Serializable
data class State(
    val entity_id: String,
    val state: String
)



if (msg.result is JsonArray) {
  for (el in msg.result) {
    val state = json.decodeFromJsonElement(el))
    ...
  }
}