Android ListView 將JSON 陣列轉換為Java List
Android ListView 是常用的顯示資料的元件,需要Java 物件作為其資料來源。然而,API 回應或從伺服器傳回的資料通常採用 JSON(JavaScript 物件表示法)的形式,其中包含陣列或資料清單。要在 ListView 中呈現此數據,需要將 JSON 陣列轉換為 Java 列表。
以下是如何在 Android 的 Java 中實現此轉換:
<code class="java">import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; ... // Instantiate an ArrayList to store the converted data ArrayList<string> list = new ArrayList(); // Get the JSON array from the JSON object JSONArray jsonArray = (JSONArray) jsonObject; // Check if the JSON array is not null if (jsonArray != null) { // Get the length of the JSON array int len = jsonArray.length(); // Iterate over the JSON array and add each element to the ArrayList for (int i = 0; i <p>在此程式碼片段中:</p> <ul> <li>JSON 回應儲存在 JSONObject 變數中。 </li> <li>我們使用 (JSONArray) 轉換從 JSONObject 提取 JSON 陣列。 </li> <li>我們確保JSON 陣列在迭代之前不為 null。 </li> <li>我們循環遍歷 JSON 數組,使用 jsonArray.get(i).toString() 將每個元素轉換為字串並將其新增至 ArrayList。 </li> </ul> <p>循環完成後,ArrayList 包含來自 JSON 數組的數據,可以將其用作 ListView 的數據源。 </p></string></code>
以上是如何將 JSON 陣列轉換為 Android ListView 的 Java 清單?的詳細內容。更多資訊請關注PHP中文網其他相關文章!