How to add / remove / edit value of kotlinx.serialization.json.JsonObject

Viewed 1288

I am currently struggling for best way to add property to existing jsonObject(kotlinx.serialization.json.JsonObject)

Even I have found that JsonObject internally has private immutable map

private val content: Map<String, JsonElement>

Scenario: Suppose I already have one jsonObject with 50 properties in it and considering jsonObject at any key can have any number of depth.

For such situation how can we efficiently perform below operations:

  1. Adding primitive properties
  2. Updating primitive properties
  3. Deleting primitive properties

FYI : Even I have found there is class called JsonObjectBuilder but it does not take existing JsonElement / JsonObject / JsonArray infact it will newly create another jsonObject.

Thanks for giving your time to read till here

https://github.com/Kotlin/kotlinx.serialization/issues/1593

1 Answers

Since this internal content map is immutable, the only way to edit JsonObject is to create new one (out of old). Luckily, there is a JsonObject constructor taking a Map, moreover JsonObject implements the Map interface itself. So I'd suggest the following idiom:

val newJsonObj = JsonObject(oldJsonObj.toMutableMap().apply {
    // edit like ordinary mutable map
})
Related