簡體   English   中英

循環遍歷多個 JsonObject

[英]Loop through multiple JsonObject

如何使用這種類型的結構遍歷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);
}

根據您的代碼,您只需獲取第一個對象的鍵和值。

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();
    }

你的 JSON 不是一個 JSONObject,而是一個 JSONArray,

你的回復應該是這個Valid 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();
}

輸出

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM