开发者

Type Safety warning with JSON Iterator

开发者 https://www.devze.com 2023-01-27 02:04 出处:网络
My problem comes from getting an Iterator from a JSONObject. Code generating error in its simplest form:

My problem comes from getting an Iterator from a JSONObject.

Code generating error in its simplest form:

String json = client.retrieveList();
JSONObject jsonList = new JSONObject(json);
Iterator<String> i = jsonList.keys();

while(i.hasNext())
{
    String next = i.next();
    开发者_JAVA百科JSONArray jsonArray = jsonList.getJSONArray(next);
    // Do stuff with jsonArray, example: jsonArray.getString(0), jsonArray.getString(1);
}

The exact warning is: Type safety: The expression of type Iterator needs unchecked conversion to conform to Iterator

So the question is how can I eradicate this warning?

Many thanks!


i realize this is an old thread, but for future searchers...

you can also infer a generic and cast the returns of the iterator methods...

Iterator<?> i = jsonList.keys();

while(i.hasNext())
{
    String next = (String) i.next();
    ...


When you mix your code with old legacy API-s you can get this kind of warnings. If you really want to "eradicate" the warning you can use the SuppressWarnings annotation. It is a good practice to leave a comment next to suppressed warning. In your case this may look like:

@SuppressWarnings("unchecked") //Using legacy API
Iterator<String> i = jsonList.keys();

Cheers!

0

精彩评论

暂无评论...
验证码 换一张
取 消