如何在java中迭代JSONArray

时间:2014-11-20 09:15:17

标签: java json parsing arrays

我想从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();
        }   

结果如下。

["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",""]

我想逐个提取值并将其分配给变量。例如1001432,05-KALENJI-P1229,KALENJI,2,2014-11-09 09:37:14.379482。这样我就可以处理每个值。请任何人帮助我

3 个答案:

答案 0 :(得分:5)

您可以使用以下代码:

//将你的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));
                        }
                    }
                }
            }

答案 1 :(得分:0)

你可以通过循环迭代数组并得到你喜欢的对象:

 JsonObject home = array.getJsonObject(index); //use index to iterate
 String num = home.getString("number"); //make number a static final variable

“number”是值的名称,最初放在

.add("number", someString);

电贺。

编辑: 我建议您阅读文档:Oracle Docthis, too.

答案 2 :(得分:0)

看起来JSON数组是2维的。试试这个:

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));
    }
}