java 使用 JSON 迭代器输入安全警告
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4296496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Type Safety warning with JSON Iterator
提问by Knossos
My problem comes from getting an Iterator from a JSONObject.
我的问题来自从 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();
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
确切的警告是:类型安全:类型 Iterator 的表达式需要未经检查的转换以符合 Iterator
So the question is how can I eradicate this warning?
所以问题是我怎样才能消除这个警告?
Many thanks!
非常感谢!
回答by momo
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();
...
回答by Lachezar Balev
When you mix your code with old legacy API-s you can get this kind of warnings. If you reallywant 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:
当您将代码与旧的遗留 API 混合时,您可能会收到此类警告。如果您真的想“消除”警告,您可以使用 SuppressWarnings 注释。在抑制警告旁边留下评论是一种很好的做法。在您的情况下,这可能如下所示:
@SuppressWarnings("unchecked") //Using legacy API
Iterator<String> i = jsonList.keys();
Cheers!
干杯!