繁体   English   中英

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

[英]javax.json: Add new JsonNumber to existing JsonObject

我想将属性添加到现有的JsonObject实例。 如果此属性是boolean ,这很容易:

JsonObject jo = ....;
jo.put("booleanProperty", JsonValue.TRUE);

但是,我还想添加一个JsonNumber但我找不到创建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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM