Is there any quick API to put a simple value into ...
# serialization
a
Is there any quick API to put a simple value into a
JsonObject
without unboxing the whole object?
the API seems pretty closed
the underlying map is private
private val content: Map<String, JsonElement>
r
content
is private but because
JsonObject
implements
Map
, you can call
toMutableMap()
on it and make your changes there, then create a new object from that map
p
Because it implements
Map
you can just use the map + operator; it'd be pretty easy to write an extension that does something like this:
Copy code
val updated = JsonObject(existing + mapOf("abc" to JsonPrimitive("def")))
The
JsonPrimitive
call is a little rough - maybe use
buildJsonObject
for the new key(s) you're adding
Copy code
fun JsonObject.update(keys: JsonObjectBuilder.() -> Unit) = JsonObject(this + buildJsonObject(keys))
in use becomes:
Copy code
existing.update {
    put("abc", "def")
}
update
is probably the wrong term since you're returning a new instance, not modifying the existing, but 🤷
a
thanks guys I was aware of some of these possibilities but all of them don't really update the instance of
JsonObject
in question. They rather create a new instance. Your suggestions are nice workarounds. But is this API supposed to be such closed that workarounds are needed? I worked a lot with
Gson
and
org.json
libraries which have such basic features out of the box. If this isn't intended, maybe I can open a PR.
r
Kotlin APIs tend to prefer immutability for this sort of thing.
👍 2
1