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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26346060/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 09:45:56  来源:igfitidea点击:

javax.json: Add new JsonNumber to existing JsonObject

javajson

提问by aRestless

I want to add properties to an existing instance of JsonObject. If this property is boolean, this is quite easy:

我想将属性添加到JsonObject. 如果这个属性是boolean,这很容易:

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

However, I also want to add a JsonNumberbut I couldn't find a way to create an instance of JsonNumber. Here's what I could do:

但是,我也想添加一个,JsonNumber但找不到创建JsonNumber. 这是我可以做的:

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 JsonNumberto an existing instance of JsonObject?

但我想不出更肮脏的方式来完成我的任务。那么 - 是否有更直接、更简洁的方法来将 a 添加JsonNumber到 的现有实例JsonObject

回答by aRestless

Okay, I just figured it out myself: You can't.

好吧,我只是自己想通了:你不能

JsonObjectis 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 JsonObjectyou'll need something like

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;
}

and then use it with

然后使用它

JsonObject jo = ...;
jo = jsonObjectToBuilder(jo).add("numberProperty", 42).build();

回答by mark786110

Try using JsonPatch

尝试使用 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);

回答by Scott Boring

JsonObject is immutable but can be copied into a JsonObjecBuilder using lambdas.

JsonObject 是不可变的,但可以使用 lambda 复制到 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