Java 循环遍历 Json 数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19018509/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 13:25:55  来源:igfitidea点击:

Java loop over Json array?

javajson

提问by Alosyius

I am trying to loop over the following JSON

我正在尝试遍历以下内容 JSON

{
    "dataArray": [{
        "A": "a",
        "B": "b",
        "C": "c"
    }, {
        "A": "a1",
        "B": "b2",
        "C": "c3"
    }]
}

What i got so far:

到目前为止我得到了什么:

JSONObject jsonObj = new JSONObject(json.get("msg").toString());

for (int i = 0; i < jsonObj.length(); i++) {
    JSONObject c = jsonObj.getJSONObject("dataArray");

    String A = c.getString("A");
    String B = c.getString("B");
    String C = c.getString("C");

}

Any ideas?

有任何想法吗?

采纳答案by Sotirios Delimanolis

In your code the element dataArrayis an array of JSON objects, not a JSON object itself. The elements A, B, and Care part of the JSON objects inside the dataArrayJSON array.

在您的代码中,元素dataArray是一个 JSON 对象数组,而不是 JSON 对象本身。元素ABCdataArrayJSON 数组中JSON 对象的一部分。

You need to iterate over the array

您需要遍历数组

public static void main(String[] args) throws Exception {
    String jsonStr = "{         \"dataArray\": [{              \"A\": \"a\",                \"B\": \"b\",               \"C\": \"c\"            }, {                \"A\": \"a1\",              \"B\": \"b2\",              \"C\": \"c3\"           }]      }";

    JSONObject jsonObj = new JSONObject(jsonStr);

    JSONArray c = jsonObj.getJSONArray("dataArray");
    for (int i = 0 ; i < c.length(); i++) {
        JSONObject obj = c.getJSONObject(i);
        String A = obj.getString("A");
        String B = obj.getString("B");
        String C = obj.getString("C");
        System.out.println(A + " " + B + " " + C);
    }
}

prints

印刷

a b c
a1 b2 c3

I don't know where msgis coming from in your code snippet.

我不知道msg你的代码片段来自哪里。

回答by Jaydeep Patel

Java Docs to the rescue:

Java Docs 来救援:

You can use http://www.json.org/javadoc/org/json/JSONObject.html#getJSONArray(java.lang.String)instead

您可以使用http://www.json.org/javadoc/org/json/JSONObject.html#getJSONArray(java.lang.String)代替

JSONArray dataArray= sync_reponse.getJSONArray("dataArray");

for(int n = 0; n < dataArray.length(); n++)
{
    JSONObject object = dataArray.getJSONObject(n);
    // do some stuff....
}