javax.json:将新的JsonNumber添加到现有的JsonObject [英] javax.json: Add new JsonNumber to existing JsonObject
问题描述
我想将属性添加到 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
,则需要类似
<$ p的内容$ p>
private JsonObjectBuilder jsonObjectToBuilder(JsonObject jo){
JsonObjectBuilder job = Json.createObjectBuilder();
for(Entry< String,JsonValue> entry:jo.entrySet()){
job.add(entry.getKey(),entry.getValue());
}
返回工作;
}
然后将其与
$ b $一起使用b
JsonObject jo = ...;
jo = jsonObjectToBuilder(jo).add(numberProperty,42).build();
I want to add properties to an existing instance of JsonObject
. If this property is boolean
, this is quite easy:
JsonObject jo = ....;
jo.put("booleanProperty", JsonValue.TRUE);
However, I also want to add a JsonNumber
but I couldn't find a way to create an instance of JsonNumber
. Here's what I could do:
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 JsonNumber
to an existing instance of JsonObject
?
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();
这篇关于javax.json:将新的JsonNumber添加到现有的JsonObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!