Is there a way to update some properties in a JSON file by parsing a
data class
that doesn't have all the properties of that file without losing the properties that are not part of the
data class
yet exist in the JSON file?
It's possible using
Json.parseToJsonElement
and manually update using
jsonObject?.toMutableMap()
The only problem that it doesn't use the same Serial name in the data class and is not type-saftey.
e
ephemient
06/23/2024, 8:19 PM
can you just merge the keys back to the json object?
Copy code
val json = Json {
ignoreUnknownKeys = true
}
val input = json.parseToJsonElement(...)
val data1: Data = json.decodeFromJsonElement(input)
val data2 = data1.copy(...)
val output = JsonObject(input.jsonObject + json.encodeToJsonElement(data2).jsonObject)
👍 1
a
Ahmed Riyadh
06/23/2024, 8:22 PM
Thank you for the suggestion. It worked as expected and efficiently, a minor thing, for
parseToJsonElement
and
encodeToJsonElement
You could also use
Json
directly instead of using the Json with ignore unknown keys.
Ahmed Riyadh
06/24/2024, 2:12 AM
A side note, for more advance use-cases where you want to update another
data class
inside your
data class
. You will have to choose to either use the one from
parseToJsonElement
or
You will have to deep merge the two JSON objects.
The only issue, if you remove something from the updated data class, you will still have it in the JSON element if it's there.