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

Android 天氣應用 JSON 解析錯誤:字段名稱變更導致資料提取失敗

     編輯:程式設計綜合問答

問題現象

Android 應用呼叫氣象 API 獲取 JSON 資料,解析時拋出 JSONException,無法取得 weather1、temp1 等字段。

API 回應實例

{
  "weatherinfo": {
    "city": "北京",
    "cityid": "101010100",
    "temp1": "3℃",
    "temp2": "-6℃",
    "weather": "晴轉多雲",
    "img1": "d0.gif",
    "img2": "n1.gif",
    "ptime": "08:00"
  }
}

錯誤原因

程式碼中使用 json.getString("weather1"),但實際 JSON 字段為 weather(無數字後綴)。同理 temp1、temp2 存在,但 weather1 不存在。

修正代碼

JSONObject weatherInfo = new JSONObject(str).getJSONObject("weatherinfo");
String city = weatherInfo.getString("city");
String temp = weatherInfo.getString("temp1");      // 正確
String weather = weatherInfo.getString("weather"); // 修正:weather1 → weather

最佳實踐

  • 使用 optString(key, default) 避免字段缺失拋出異常。
  • 引入 Gson 或 Moshi 等庫自動映射至資料類別,減少手動解析錯誤。
  • 單元測試覆蓋 API 回應結構變更場景。
  • 網路請求採用 OkHttp + Coroutines/Flow 替代已棄用的 DefaultHttpClient。

補充說明

原代碼使用的 HttpClient、HttpParams 等類別在 API 22+ 已棄用,建議遷移至現代網路庫。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved