我正在嘗試對一些代碼進行書面報告,我在 Youtube 上找到了一個。但是,我不明白這個回圈是如何作業的。我知道它遍歷串列中的每個專案并獲取每個變數的每個值,然后將所有值添加到串列中,該串列顯示在 Android Studio 的 XML 視圖中。如果有人可以分解正在發生的事情,將不勝感激!
private void setupData() {
RequestQueue queue = Volley.newRequestQueue(this);
String url =" - hidden - ";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("data");
for (int i = 0; i < jsonArray.length() ; i ){
JSONObject jo = jsonArray.getJSONObject(i);
System.out.println(jo.toString());
Supplier supplier = new Supplier(String.valueOf(jo.getInt("id")), jo.getString("name"), jo.getString("url"), jo.getString("specialization"), jo.getString("country"), jo.getInt("rating"));
supplierList.add(supplier);
System.out.println(jsonArray.length());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println(error.toString());
System.out.println("That didn't work!");
}
});
queue.add(request);
}
uj5u.com熱心網友回復:
盡管您可以簡單地閱讀 JSONObject 類和屬于該包的所有其他類。但是,讓我在這里舉例說明我的理解。這是正在接收的回應 json。
{
"data": [
{
"id": 1,
"name": "ABCD",
"url": "https://www.stackoverflow.com",
"specialization": "master",
"country": "India",
"rating" : 5
},
{
"id": 1,
"name": "ABCD",
"url": "https://www.stackoverflow.com",
"specialization": "master",
"country": "India",
"rating" : 5
}]
}
代碼正在嘗試處理這個完整的 json。它首先將“資料”物件讀入一個陣列,因為它表示一個陣列,然后將該陣列中的每個物件塊轉換為一個供應商模型類,然后將其添加到供應商串列中。
JSONArray jsonArray = response.getJSONArray("data"); // reads the "data" attribute.
for (int i = 0; i < jsonArray.length() ; i ){ // Iterates every block, every block inside this array represent a JSONObject
JSONObject jo = jsonArray.getJSONObject(i); // Reads every block using simple loop and index logic
System.out.println(jo.toString());
Supplier supplier = new Supplier(String.valueOf(jo.getInt("id")), jo.getString("name"), jo.getString("url"), jo.getString("specialization"), jo.getString("country"), jo.getInt("rating")); // Reads the attributes from the JSONObject to create an instance of Supplier class
supplierList.add(supplier); // Adds the supplier instance to the list
System.out.println(jsonArray.length());
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/439172.html
標籤:爪哇 for循环 要求 jsonobject请求
