从JSON对象创建一个ArrayList

3

我有一个JSON,就像下面图片中所示,存储在MYJSON中--

enter image description here

我的计划是检索所有childObject0中的对象,并将它们存储在ArrayList中,以便稍后处理。所以我做了以下操作-

ArrayList<String> childLists = new ArrayList<String>();
 try {
       JSONArray childArray = MYJSON.getJSONArray("childObject0");
       for (int i = 0; i<jArray.length(); i++
                 ) {
           //I lost it here! How can I append to `childList` from `childArray`?
                
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

无法弄清如何添加。这是正确的方法吗?childObject0是动态的,计数随时更改。谢谢。

1个回答

3

由于childObject0中的每个对象都是json格式,因此可以将其存储为一个ArrayList<JSONObject>。这样处理对象比将其作为字符串更容易。

ArrayList<JSONObject> childList = new ArrayList<JSONObject>();
try {
    JSONArray childArray = MYJSON.getJSONArray("childObject0");
    for (int i = 0; i < childArray.length(); i++) {
        childList.add(childArray.getJSONObject(i));
    }
} catch (JSONException e) {
    e.printStackTrace();
}

1
使用 ArrayList<JSONObject> 拯救了这一天! - envyM6

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接