首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android JSON 解析報錯:JSONArray 強轉 JSONObject 導致類型不匹配

     編輯:程式設計綜合問答

錯誤現象

Logcat 顯示第 37 行報錯,代碼嘗試將服務端返回的 JSON 對象強轉為數組:

String jsonData = (String) msg.obj;
JSONArray jsonArray = new JSONArray(jsonData); // 崩潰

報錯截圖

原因分析

服務端返回的是 **JSONObject** (以 { 開頭),而非 JSONArray (以 [ 開頭)。直接 `new JSONArray(jsonData)` 拋出 JSONException。

正確解析流程

  1. 先解析為 JSONObject。
  2. 從中取出數據數組鍵 (如 "posts"、"data"、"list")。
  3. 再獲取 JSONArray 遍歷。

代碼修正

try {
    JSONObject root = new JSONObject(jsonData);
    // 假設數據在 "posts" 字段
    JSONArray jsonArray = root.getJSONArray("posts");
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject item = jsonArray.getJSONObject(i);
        String title = item.getString("title");
        // ... 其他字段
        newsList.add(new News(title, ...));
    }
    adapter.notifyDataSetChanged();
} catch (JSONException e) {
    e.printStackTrace();
}

調試建議

  • 打印 jsonData 確認結構:System.out.println(jsonData);
  • 使用在線 JSON 格式化工具 (如 json.cn) 貼入響應文本,直觀查看層級。
  • 若字段名不固定,用 root.names() 遍歷鍵名。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved