'How to parse generic key with kotlin serialization from JSON
I am struggling with come up with idea how to properly parse JSON like this:
{
"generic_key": { "version":1, "ttl":42 }
}
where expected kotlin class should look like this:
@Serializable
data class Config(val version: Int, val ttl: Long) {
@Transient
var key: String? = null // <== here comes generic_key
}
UPDATE
What I want to achieve is to get a kotlin class from string JSON and I don't know what key will be used as "generic_key".
UPDATE 2
Even something like this is okey for me:
@Serializable
data class ConfigWrapper(val map: Map<String, Config>)
Where there would be map with single item with key from jsonObject (e.g. generic_key) and with rest parsed with standard/generated Config.serializer.
Solution 1:[1]
Use the following data classes
data class Config(
@SerializedName("generic_key" ) var genericKey : GenericKey? = GenericKey()
)
data class GenericKey (
@SerializedName("version" ) var version : Int? = null,
@SerializedName("ttl" ) var ttl : Int? = null
)
Solution 2:[2]
If the key is dynamic and different, the map structure should be fine
@Serializable
data class Config(val version: Int, val ttl: Long)
val result = JsonObject(mapOf("generic_key" to Config(1, 42)))
Solution 3:[3]
At the end this works for me, but if there is more straight forward solution let me know.
private val jsonDecoder = Json { ignoreUnknownKeys = true }
private val jsonConfig = "...."
val result = jsonDecoder.parseToJsonElement(jsonConfig)
result.jsonObject.firstNonNullOf { (key, value) ->
config = jsonDecoder.decodeFromJsonElement<Config>(value).also {
it.key = key // this is generic_key (whatever string)
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Siddarth Jain |
| Solution 2 | Sergey M |
| Solution 3 | ThinkDeep |
