javax.json:将新的JsonNumber添加到现有的JsonObject

问题描述 投票:14回答:3

我想在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实例中?

java json
3个回答
27
投票

好吧,我只是想出了自己:你做不到。

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();

1
投票

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

1
投票

尝试使用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);
© www.soinside.com 2019 - 2024. All rights reserved.