a

    Azur Haljeta

    1 year ago
    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>
    russhwolf

    russhwolf

    1 year ago
    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

    Paul Griffith

    1 year ago
    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:
    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
    fun JsonObject.update(keys: JsonObjectBuilder.() -> Unit) = JsonObject(this + buildJsonObject(keys))
    in use becomes:
    existing.update {
        put("abc", "def")
    }
    update
    is probably the wrong term since you're returning a new instance, not modifying the existing, but 🤷
    a

    Azur Haljeta

    1 year ago
    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.
    russhwolf

    russhwolf

    1 year ago
    Kotlin APIs tend to prefer immutability for this sort of thing.