简体   繁体   中英

Remove a key-value pair from javax.json.JsonObject

I'm using JDK 1.8.0_101 and added javax.json.jar to classpath. The below compiles just fine but throws an error. It looks like the remove() method has not been implemented.

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?

JsonObject is immutable. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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