如何循环在Android中使用Java和org.json这个JSON数组?数组、Java、Android、org

2023-09-06 19:35:09 作者:我不要在庸碌中老去

我的JSON字符串如下所示(包含在一个名为字符串变量 sJSON ):

My JSON string looks like this (contained in a string variable called sJSON):

[
    {"id":284}
],
[
    {"name":John,"surname":Doe},
    {"name":Jane,"surname":Doe}
]

我能解析第一个数组这样的(使用Java和进口org.json):

I'm able to parse the first array like this (using Java and importing org.json):

JSONArray arrJSON = new JSONArray(sJSON);
JSONObject jsonGeneralData = new JSONObject(arrJSON.get(0).toString());

String sResult = jsonGeneralData.get("id").toString();

这是返回预期的结果,这是284,我努力让项目的第二阵列,并遍历它们。我不知道如果我的JSON字符串格式不正确,或者如果我试图访问了错误的方式。下面是我的尝试:

That returns the expected result, which is 284. I'm struggling to get the second array of items, and iterate through them. I'm not sure if my JSON string is malformed, or if I'm trying to access it the wrong way. Here's what I tried:

JSONObject jsonPersonData = new JSONObject(arrJSON.get(1).toString());

这是据我得到的,我无法弄清楚如何通过个别项目第二次循环数组中。

This is as far as I got, I can't figure out how to loop through the individual items inside the second array.

编辑:

看来这行只解析第一个字符串中的方括号:

It seems that this line only parses the first string in the square brackets:

JSONArray arrJSON = new JSONArray(sJSON);

无论是JSON是错误的(与上面的例子),或者它不是解析它是否正确?我已经成功地解决了这样做的字符串分割的问题,并把他们各自在自己的 JSONArray ,但我不认为这是做事情的最好方法

Either the JSON is wrong (same example as above), or it's not parsing it correctly? I've managed to solve the problem by doing a split on the string and put them each in their own JSONArray, but I don't think that's the best way of doing things.

推荐答案

您希望是这样的。

JSONArray jsonArray = new JSONArray(sJSON);
JSONArray jsonPersonData = jsonArray.getJSONArray(1);
for (int i=0; i<jsonPersonData.length(); i++) {
    JSONObject item = jsonPersonData.getJSONObject(i);
    String name = item.getString("name");
    String surname = item.getString("surname");
}