I want to add properties to an existing instance of JsonObject
. If this property is boolean
, this is quite easy:
JsonObject jo = ..
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 path = Json.createPatchBuilder()
.add("/last","Doe")
.build();
jo = path.apply(jo);
System.out.println(jo);
JsonObject is immutable but can be copied into a JsonObjecBuilder using lambdas.
JsonObject source = ...
JsonObjectBuilder target = Json.createObjectBuilder();
source.forEach(target::add); // copy source into target
target.add("name", "value"); // add or update values
JsonObject destination = target.build(); // build destination