循环遍历多个JsonObject

时间:2018-02-04 20:52:05

标签: java android json

如何使用此类结构循环 JSON

{
    "name": "Jane John Doe",
    "email": "janejohndoe@email.com"
},
{
    "name": "Jane Doe",
    "email": "janedoe@email.com"
},
{
    "name": "John Doe",
    "email": "johndoe@email.com"
}

我尝试了下面的代码,但我只得到了最后一项。

List<Object> response = new ArrayList<>();

JSONObject jsonObject = new JSONObject(json);
Iterator<?> iterator = jsonObject.keys();
while (iterator.hasNext()) {
    Object key = iterator.next();
    Object value = jsonObject.get(key.toString());

    response.add(value);
}

2 个答案:

答案 0 :(得分:1)

根据您的代码,您只需获取第一个对象的键和值。

JSONObject jsonObject = new JSONObject(json);

从上面的代码中,您只需从JSON获得第一个对象。

Iterator<?> iterator = jsonObject.keys();
while (iterator.hasNext()) {
Object key = iterator.next();
Object value = jsonObject.get(key.toString());
response.add(value);
}

从上面的代码中,您将获得第一个JSON对象的键和值。

现在,如果您想获取所有对象值,则必须按以下方式更改代码:

更改JSON,如下所示:

[{
  "name": "Jane John Doe",
  "email": "janejohndoe@email.com"
},
{
  "name": "Jane Doe",
  "email": "janedoe@email.com"
},
{
  "name": "John Doe",
  "email": "johndoe@email.com"
}]

按以下方式更改java代码:

List<HashMap<String,String>> response = new ArrayList<>();
JSONArray jsonarray = null;
    try {
        jsonarray = new JSONArray(json);
        for(int i=0;i<jsonarray.length();i++) {
            JSONObject jsonObject = jsonarray.getJSONObject(i);
            Iterator<?> iterator = jsonObject.keys();
            HashMap<String,String> map = new HashMap<>();
            while (iterator.hasNext()) {
                Object key = iterator.next();
                Object value = jsonObject.get(key.toString());
                map.put(key.toString(),value.toString());

            }
            response.add(map);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

答案 1 :(得分:0)

您的JSON不是JSONObject,而是JSONArray,

您的回复应该是有效JSON

[{
    "name": "Jane John Doe",
    "email": "janejohndoe@email.com"
}, {
    "name": "Jane Doe",
    "email": "janedoe@email.com"
}, {
    "name": "John Doe",
    "email": "johndoe@email.com"
}]

解析代码片段

try
{
    JSONArray jsonArray = new JSONArray("Your Json Response");

    for (int i = 0; i < jsonArray.length(); i++) {

        JSONObject jsonObject = jsonArray.getJSONObject(i);

        String userName = jsonObject.getString("name");
        String userEmail = jsonObject.getString("email");

        Log.i("TAG Name " + i, " : " + userName);
        Log.i("TAG Mail " + i, " : " + userEmail);

    }
} 
catch (JSONException e) 
{
    // TODO Auto-generated catch block
    e.printStackTrace();
}

<强>输出

enter image description here