如何在java中迭代JSONArray
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27035715/
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
How to iterate JSONArray in java
提问by Kathirvel Appusamy
I would like to extract the values from JSONArray. JSONArray has N number of rows and columns.
我想从 JSONArray 中提取值。JSONArray 有 N 个行和列。
ObjectMapper mapper = new ObjectMapper();
DynamicForm dynamicForm = new DynamicForm();
dynamicForm = dynamicForm.bindFromRequest();
Dynamic dynamic = dynamicForm.get();
//List<OneModel> list = new ArrayList<OneModel>();
//List iterate=new ArrayList();
String data = dynamic.getData().get("content").toString();
try {
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
System.out.println(jsonArray.get(i));
} }catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Its resulting as follows.
其结果如下。
["1001432","05-KALENJI-P1229","KALENJI","2","2014-11-09 09:37:14.379482",""],
["1001432","05-KALENJI-P1228","KALENJI","1","2014-11-09 09:37:14.379482",""],
["1001432","05-KALENJI-P1227","KALENJI","5","2014-11-09 09:37:14.379482",""]
I would like to extract one by one values and assign it to variable. for example 1001432,05-KALENJI-P1229,KALENJI,2,2014-11-09 09:37:14.379482. So that i can process each values. Please any one help me in the same
我想一一提取值并将其分配给变量。例如 1001432,05-KALENJI-P1229,KALENJI,2,2014-11-09 09:37:14.379482。这样我就可以处理每个值。请任何人帮助我
采纳答案by Krunal Indrodiya
You can use the following code:
您可以使用以下代码:
//put your json in the string variable "data"
//把你的json放在字符串变量“data”中
JSONArray jsonArray=new JSONArray(data);
if(jsonArray!=null && jsonArray.length()>0){
for (int i = 0; i < jsonArray.length(); i++) {
JSONArray childJsonArray=jsonArray.optJSONArray(i);
if(childJsonArray!=null && childJsonArray.length()>0){
for (int j = 0; j < childJsonArray.length(); j++) {
System.out.println(childJsonArray.optString(j));
}
}
}
}
回答by HymansOnF1re
Your can iterate over the array via a loop and get your objects like this:
您可以通过循环遍历数组并获得如下对象:
JsonObject home = array.getJsonObject(index); //use index to iterate
String num = home.getString("number"); //make number a static final variable
The "number" is the name for the value, which was originally put in with
“数字”是值的名称,它最初与
.add("number", someString);
Greets.
问候。
edit: I recommend to read the docu: Oracle Docand this, too.
编辑:我建议您也阅读文档:Oracle Doc和这个。
回答by jmn
It looks like the JSON array is 2 dimensional. Try this:
看起来 JSON 数组是二维的。尝试这个:
JSONArray outerArray = new JSONArray(data);
for (int i = 0; i < outerArray.length(); i++) {
JSONArray innerArray = outerArray.getJSONArray(i);
for (int j = 0; j < outerArray.length(); j++) {
System.out.println(innerArray.get(j));
}
}