javax.json: Add new JsonNumber to existing JsonObject

Okay, I just figured it out myself: You can't.

JsonObject is supposed to be immutable. Even if JsonObject.put(key, value) exists, at runtime this will throw an UnsupportedOperationException. So if you want to add a key/value-pair to an existing JsonObject you'll need something like

private JsonObjectBuilder jsonObjectToBuilder(JsonObject jo) {
    JsonObjectBuilder job = Json.createObjectBuilder();

    for (Entry<String, JsonValue> entry : jo.entrySet()) {
        job.add(entry.getKey(), entry.getValue());
    }

    return job;
}

and then use it with

JsonObject jo = ...;
jo = jsonObjectToBuilder(jo).add("numberProperty", 42).build();

Try using JsonPatch

String json ="{\"name\":\"John\"}";
JsonObject jo = Json.createReader(new StringReader(json)).readObject();
JsonPatch patch = Json.createPatchBuilder()
        .add("/last","Doe")
        .build();
jo = patch.apply(jo);
System.out.println(jo);

Tags:

Java

Json