-1

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

2
  • Are you using org.json.JSONObject or org.json.simple.JSONObject? Commented Dec 23, 2018 at 8:31
  • @D.B. org.json.JSONObject Commented Dec 23, 2018 at 8:33

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

4 Comments

But then I get a warning Type safety: The expression of type Iterator needs unchecked conversion to conform to Iterator<String>
I'm using the latest version - org.json:json:20180813 and I don't get any such warning. Please provide more details about your setup.
This is a warning in Eclipse, basically you cast to String although it's not safe, you don't define JSONObject with String keys. BTW did you downvote?
@user7294900 JSONObject has hardcoded String keys. The code given in the answer should not cause such a warning. Generics are used since version 2014-05-03. Please upgrade your JSON-java dependency.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.