[英]Remove a key-value pair from javax.json.JsonObject
I'm using JDK 1.8.0_101 and added javax.json.jar to classpath. 我正在使用JDK 1.8.0_101并将javax.json.jar添加到classpath。 The below compiles just fine but throws an error.
下面编译得很好,但抛出错误。 It looks like the remove() method has not been implemented.
看起来像remove()方法还没有实现。
public class Test{
public static void main(String[] args) {
javax.json.JsonObject o = javax.json.Json.createObjectBuilder().add("a", 1).add("b", 2).build();
try {
o.remove("a");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
This is the output: 这是输出:
java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableMap$UnmodifiableEntrySet$1.remove(Collections.java:1664)
at java.util.AbstractMap.remove(AbstractMap.java:254)
at Test.main(Test.java:5)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
How can I fix it or when can I expect this method to be implemented? 我该如何解决它或何时能够实现此方法? Am I using an old version of the javax.json library?
我使用旧版本的javax.json库吗?
JsonObject is immutable. JsonObject是不可变的。 So, you can create a new object with or without a property.
因此,您可以创建具有或不具有属性的新对象。
To remove a property: 要删除属性:
public static JsonObject removeProperty(JsonObject origin, String key){
JsonObjectBuilder builder = Json.createObjectBuilder();
for (Map.Entry<String,JsonValue> entry : origin.entrySet()){
if (entry.getKey().equals(key)){
continue;
} else {
builder.add(entry.getKey(), entry.getValue());
}
}
return builder.build();
}
And to add a new property: 并添加一个新属性:
public static JsonObject addProperty(JsonObject origin, String key, String value){
JsonObjectBuilder builder = Json.createObjectBuilder();
for (Map.Entry<String,JsonValue> entry : origin.entrySet()){
builder.add(entry.getKey(), entry.getValue());
}
builder.add(key, value);
return builder.build();
}
You can remove any element by using JsonObjectBuilder. 您可以使用JsonObjectBuilder删除任何元素。
For example: 例如:
public class Test{
public static void main(String[] args) {
javax.json.JsonObject full = javax.json.Json.createObjectBuilder().add("a", 1).add("b", 2).build();
full = javax.json.Json.createObjectBuilder(full).remove("a").build();
System.out.println(full); // return {"b":2}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.