Generify JSONObject string keys

2020-05-09 17:30发布

问题:

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