Json数组上的Java循环?

Alo*_*ius 27 java json

我试图循环以下 JSON

{
    "dataArray": [{
        "A": "a",
        "B": "b",
        "C": "c"
    }, {
        "A": "a1",
        "B": "b2",
        "C": "c3"
    }]
}
Run Code Online (Sandbox Code Playgroud)

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

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

}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Sot*_*lis 47

在您的代码中,元素dataArray是JSON对象的数组,而不是JSON对象本身.的元素A,BC为内部的JSON对象的一部分dataArrayJSON阵列.

你需要迭代数组

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

版画

a b c
a1 b2 c3
Run Code Online (Sandbox Code Playgroud)

我不知道msg您的代码段中的来源.


Jay*_*tel 5

抢救Java文档:

您可以使用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....
}
Run Code Online (Sandbox Code Playgroud)