I want to add properties to an existing instance of JsonObject. If this property is boolean, this is quite easy:
JsonObject jo = ....;
jo.put("booleanProperty", JsonValue.TRUE);
However, I also want to add a JsonNumber but I couldn't find a way to create an instance of JsonNumber. Here's what I could do:
JsonObjectBuilder job = Json.createObjectBuilder();
JsonNumber jn = job.add("number", 42).build().getJsonNumber("number");
jo.put("numberProperty", jn);
But I couldn't think of a more dirty way to accomplish my task. So - is there are more direct, cleaner approach to add a JsonNumber to an existing instance of 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With