我想在JsonObject
的现有实例中添加属性。如果这个属性是boolean
,这很容易:
JsonObject jo = ....;
jo.put("booleanProperty", JsonValue.TRUE);
但是,我也想添加一个JsonNumber
,但我找不到创建JsonNumber
实例的方法。这是我能做的:
JsonObjectBuilder job = Json.createObjectBuilder();
JsonNumber jn = job.add("number", 42).build().getJsonNumber("number");
jo.put("numberProperty", jn);
但我想不出一个更脏的方式来完成我的任务。那么 - 是否有更直接,更清洁的方法将JsonNumber
添加到现有的JsonObject
实例中?
好吧,我只是想出了自己:你做不到。
JsonObject
应该是不变的。即使JsonObject.put(key, value)
存在,在运行时这将抛出UnsupportedOperationException
。因此,如果你想为现有的JsonObject
添加一个键/值对,你需要类似的东西
private JsonObjectBuilder jsonObjectToBuilder(JsonObject jo) {
JsonObjectBuilder job = Json.createObjectBuilder();
for (Entry<String, JsonValue> entry : jo.entrySet()) {
job.add(entry.getKey(), entry.getValue());
}
return job;
}
然后用它
JsonObject jo = ...;
jo = jsonObjectToBuilder(jo).add("numberProperty", 42).build();
JsonObject是不可变的,但可以使用lambdas复制到JsonObjecBuilder中。
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
尝试使用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);