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

Android JSON 解析 JSONObject 獲取 success 字段異常的結構不匹配問題

     編輯:程式設計綜合問答

問題根因

服務端返回 JSON 結構:


{
  "tbl_user": {
    "0": { "id": "195", ... },
    "1": { "id": "196", ... },
    "success": 1
  }
}

客戶端代碼:


JSONObject json = jParser.makeHttpRequest(...);
int success = json.getInt("success"); // 拋 JSONException:根對象無 "success" 鍵

"success" 位於 "tbl_user" 內部,而非根對象。

服務端修正(推薦):調整 JSON 結構


// PHP 修正
$users = $stmt->fetchAll(PDO::FETCH_OBJ);
$response = [
    "tbl_user" => $users,
    "success" => 1 // 移至根層級
];
echo json_encode($response);

返回:


{
  "tbl_user": [ {...}, {...} ],
  "success": 1
}

客戶端即可直接 json.getInt("success")。

客戶端兼容舊結構(若無法改服務端)


JSONObject json = jParser.makeHttpRequest(...);
try {
    JSONObject tblUser = json.getJSONObject("tbl_user");
    int success = tblUser.getInt("success"); // 從子對象獲取
    if (success == 1) {
        // 遍歷 tbl_user 的鍵("0", "1", "2")
        Iterator keys = tblUser.keys();
        while (keys.hasNext()) {
            String key = keys.next();
            if ("success".equals(key)) continue; // 跳過 success 字段
            JSONObject user = tblUser.getJSONObject(key);
            String id = user.getString("id");
            String name = user.getString("fname");
            // ...
        }
    }
} catch (JSONException e) {
    e.printStackTrace();
}

最佳實踐建議

  1. 統一響應格式:{ "code": 200, "data": {...}, "msg": "" },success 放根層級。
  2. 數組而非對象映射:列表用 JSON Array [...],避免 "0": {...}, "1": {...} 非標準結構。
  3. 客戶端容錯:optInt("success", -1) 避免異常,配合 has("success") 判斷。
  4. 使用 Gson/Moshi:直接映射數據類,自動處理巢狀結構、類型轉換、異常安全。

Gson 映射示例


data class UserResponse(
    val success: Int,
    val tbl_user: List // 自動解析數組
)

data class User(
    @SerializedName("id") val id: String,
    @SerializedName("fname") val firstName: String,
    @SerializedName("lname") val lastName: String
)

// 解析
UserResponse response = new Gson().fromJson(jsonString, UserResponse.class);
if (response.success == 1) {
    for (User user : response.tbl_user) { ... }
}

總結

JSON 結構不匹配是導致 getInt 異常的主因。**服務端應輸出標準化結構(success 在根層、列表用數組)**,客戶端改用 Gson 等庫自動映射,徹底消除手動解析錯誤。

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