場景:HTTP 響應返回 JSON 數組,需提取其中對象的 NeededString 字段值。本文演示標準解析流程與常見陷阱。
[
{
"Date": "2012-1-4T00:00:00",
"keywords": null,
"NeededString": "this is the sample string I am needed for my project",
"others": "not needed"
}
]
頂層是 **JSONArray**,包含一個 **JSONObject**。
String jsonResponse = ...; // HTTP 響應字符串
try {
// 1. 解析頂層數組
JSONArray jsonArray = new JSONArray(jsonResponse);
// 2. 獲取第一個對象(根據業務可能需遍歷)
JSONObject jsonObject = jsonArray.getJSONObject(0);
// 3. 安全提取目標字段
if (jsonObject.has("NeededString") && !jsonObject.isNull("NeededString")) {
String neededString = jsonObject.getString("NeededString");
// 使用 neededString...
Log.d("JSON", "NeededString: " + neededString);
}
} catch (JSONException e) {
Log.e("JSON", "Parse error", e);
}
JSONArray,再 JSONObject,切勿直接 new JSONObject(jsonResponse)。has() + isNull() 雙重判斷,避免 getString() 拋異常。\",實際網絡響應無需手動轉義。// 定義數據類
class ResponseItem {
String Date;
String NeededString;
String others;
}
// 一鍵解析
Type listType = new TypeToken<List<ResponseItem>>(){}.getType();
List<ResponseItem> list = new Gson().fromJson(jsonResponse, listType);
String needed = list.get(0).NeededString;
掌握標準解析與現代庫用法,靈活應對各類 JSON 結構。