服務端返回 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" 內部,而非根對象。
// 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();
}
{ "code": 200, "data": {...}, "msg": "" },success 放根層級。[...],避免 "0": {...}, "1": {...} 非標準結構。optInt("success", -1) 避免異常,配合 has("success") 判斷。
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 等庫自動映射,徹底消除手動解析錯誤。