Generify JSONObject string keys

点点圈 提交于 2019-12-04 06:58:24

问题


I have existing code which use org.json.JSONObject's Iterator

JSONObject obj = new JSONObject();
obj.put("key1", "value1");
obj.put("key2", "value2");
Iterator keys = obj.keys();
...

With compile warning

Iterator is a raw type. References to generic type Iterator<E> should be parameterized

I can update to generic version:

Iterator<?> keys = obj.keys();

But isn't there a way to "generify" JSONObject with String keys?

I find this answer but its suggestion doesn't compiled

JSONObject<String,Object> obj=new JSONObject<String,Object>();

EDIT

Using Iterator<String> keys = obj.keys(); I'm getting a type safety warning:

Type safety: The expression of type Iterator needs unchecked conversion to conform to Iterator<String>

Also using Eclipse Infer generics doesn't execute any code changes


回答1:


The answer you provided a link to is using a different class than the one you are using. If you look at the source for org.json.JSONObject you'll find the following:

public Iterator<String> keys() {
    return this.keySet().iterator();
}

Which means you can write the following code:

    JSONObject obj = new JSONObject();
    obj.put("key1", "value1");
    obj.put("key2", "value2");
    Iterator<String> keys = obj.keys();

    while(keys.hasNext()){
        System.out.println(keys.next());
    }

and it will generate the following output:

key1
key2


来源:https://stackoverflow.com/questions/53901969/generify-jsonobject-string-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!