Android 應用呼叫氣象 API 獲取 JSON 資料,解析時拋出 JSONException,無法取得 weather1、temp1 等字段。
{
"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) 避免字段缺失拋出異常。DefaultHttpClient。原代碼使用的 HttpClient、HttpParams 等類別在 API 22+ 已棄用,建議遷移至現代網路庫。