I (unfortunately) have to deserialize a structure ...
# serialization
k
I (unfortunately) have to deserialize a structure which looks like the following.
Copy code
"divisions": {
    (key): {
      "name": string,
      "alsoKnownAs": [string],
      "officeIndices": [unsigned integer]
    }
  },
I only care about the value of
(key)
which is a dynamic string. I was originally deserializing this to a
Map<String, String>
but for obvious reasons ran into edge cases when the
alsoKnownAs
and
officeIndices
fields came back in a response. Is there a way to deserialize to
Any?
if I don't care about the actual value here, only the key?
j
JsonElement
You could also write a custom serializer and deserialize to Set<String>
Easiest way would be to delegate to Map<String, JsonElement> and then call keys
Obviously that's a one-way conversion, but I do that all the time and just throw in the serialize codepath
e
just tell json to ignore unknown keys. this should work regardless of what's inside
...
as long as it's well-formed:
Copy code
@Serializable data class Structure(
    val divisions: Map<String, Unit>
)

val json = Json {
    ignoreUnknownKeys = true
}
json.decodeFromString<Structure>(
    """
    {
      "divisions": {
        "foo": { ... },
        "bar": { ... }
      }
    }
    """
)
j
It's too bad that's global. Would be nice to opt in only at that specific serializer
k
Thanks all!