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

Android JSON 解析實戰:從 HTTP 響應中精準提取目標字符串字段

     編輯:程式設計綜合問答

場景: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() 拋異常。
  • 轉義處理:Java 字符串中雙引號需轉義 \",實際網絡響應無需手動轉義。

進階:Gson 自動映射(推薦)

// 定義數據類
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 結構。

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