从javax.json.JsonObject移除键/值对 [英] Remove a key-value pair from javax.json.JsonObject

查看:252
本文介绍了从javax.json.JsonObject移除键/值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 JDK 1.8.0_101 ,并将 javax.json.jar 添加到类路径中.下面的代码编译得很好,但是会引发错误.看来 remove()方法尚未实现.

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

这是输出:

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)

该如何解决?何时可以实现此方法?我是否在使用旧版本的javax.json库?

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是不可变的.因此,您可以创建一个带有或不带有属性的新对象.

JsonObject is immutable. So, you can create a new object with or without 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();
}

并添加新属性:

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

这篇关于从javax.json.JsonObject移除键/值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆