https://kotlinlang.org logo
#serialization
Title
# serialization
c

Charles Flynn

11/23/2023, 10:39 AM
I'm writing some code to add a new field to a remote document. In pseudocode javascript it would look something like:
Copy code
document = client.get(id).body
document.data.myNewField = 42
client.put(id, document)
The document i'm retrieving has a large number of fields including lists, nested objects, etc. The field i'm updating is itself a nested field. What's the best way of approaching this in Kotlin? I can't make a serializable data class - the model is too large and I don't care about the vast majority of it except that I send it all back as I found it. I can use code something like this to fulfil my objective.
Copy code
val response: JsonObject = client.get("http...").body()

    val updated = JsonObject(response.toMutableMap().apply {
        put("data", JsonObject(response["data"]!!.jsonObject.toMutableMap().apply {
            put("myNewField", JsonPrimitive("Hello World"))
        }))
    })
It seems to work but it feels really ugly. This feels like a common use case (call remote GET, modify, PUT back) so I was just wondering if i'm missing a slightly simpler approach to it.