Java Foreach 与 JSONArray 和 JSONObject
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33215539/
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
Foreach with JSONArray and JSONObject
提问by Jacobian
I'm using org.json.simple.JSONArray
and org.json.simple.JSONObject
. I know that these two classes JSONArray
and JSONObject
are incompatible, but still I want to do quite a natural thing - I want to for-each over JSONArray
parsing at each iteration step one JSONObject
(nested inside that JSONArray
). I try to do it like so:
我正在使用org.json.simple.JSONArray
和org.json.simple.JSONObject
。我知道,这两个类JSONArray
和JSONObject
是不相容的,但我仍然希望做的相当自然的事情-我想换了每一个JSONArray
在每个迭代步骤一解析JSONObject
(嵌套内部的JSONArray
)。我试着这样做:
JSONArray arr = ...; // <-- got by some procedure
for(JSONObject o: arr){
parse(o);
}
When I try to compile this code, indeed I get "incompatible types" error, even though it looks so natural. So, my question is what is the best way to iterate through JSONArray
?
当我尝试编译这段代码时,确实出现了“不兼容的类型”错误,尽管它看起来很自然。所以,我的问题是迭代的最佳方式是什么JSONArray
?
采纳答案by RealSkeptic
Apparently, org.json.simple.JSONArray
implements a rawIterator. This means that each element is considered to be an Object
. You can try to cast:
显然,org.json.simple.JSONArray
实现了一个原始的迭代器。这意味着每个元素都被认为是一个Object
. 您可以尝试投射:
for(Object o: arr){
if ( o instanceof JSONObject ) {
parse((JSONObject)o);
}
}
This is how things were done back in Java 1.4 and earlier.
这就是 Java 1.4 及更早版本中的处理方式。
回答by dguay
回答by Prasad Khode
Make sure you are using this org.json: https://mvnrepository.com/artifact/org.json/json
确保您正在使用此 org.json:https://mvnrepository.com/artifact/org.json/json
if you are using Java 8 then you can use
如果您使用的是 Java 8,那么您可以使用
import org.json.JSONArray;
import org.json.JSONObject;
JSONArray array = ...;
array.forEach(item -> {
JSONObject obj = (JSONObject) item;
parse(obj);
});
Just added a simple test to prove that it works:
刚刚添加了一个简单的测试来证明它有效:
Add the following dependency into your pom.xml
file (To prove that it works, I have used the old jar which was there when I have posted this answer)
将以下依赖项添加到您的pom.xml
文件中(为了证明它有效,我使用了发布此答案时存在的旧 jar)
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
And the simple test code snippet will be:
简单的测试代码片段将是:
import org.json.JSONArray;
import org.json.JSONObject;
public class Test {
public static void main(String args[]) {
JSONArray array = new JSONArray();
JSONObject object = new JSONObject();
object.put("key1", "value1");
array.put(object);
array.forEach(item -> {
System.out.println(item.toString());
});
}
}
output:
输出:
{"key1":"value1"}