Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android JSON 解析完全攻略:從概念到實戰範例

編輯:關於 Android 程式設計

JSON 是一種輕量級的資料交換格式,可讀性佳、易於撰寫,幾乎所有主流語言都支援,因而成為跨平台傳遞資料的熱門選擇。本文從 JSON 與 XML 的比較談起,再帶你逐一拆解 Android 內建的 org.json 套件,最後用一個完整範例收尾。

JSON 對比 XML

兩者的資料可讀性相當、解析手段都豐富,但 JSON 的資料體積更小、與 JavaScript 互動更方便、速度也遠快於 XML;代價是它對資料的描述性略遜於 XML。

android 提供的 JSON 解析類

Android 的 JSON 相關類別都在 org.json 套件下:

• JSONObject:代表一個 JSON 物件,是最基本的單位,以 Key/Value 成對存在,對外以標準字串呈現。
• JSONStringer:JSON 文字建構器,能嚴格按照語法規則建立 JSON,避免格式錯誤導致異常。
• JSONArray:代表一組有序數值,以中括號包裹、逗號分隔,支援 get/opt/put 等方法。
• JSONTokener:JSON 解析類。
• JSONException:JSON 相關的異常。

用 JSONObject、JSONArray 建立 JSON

 try { JSONObject person = new JSONObject(); JSONArray phone = new JSONArray(); phone.put("12345678").put("87654321"); person.put("phone", phone); person.put("name", "yuanzhifei89"); person.put("age", 100); JSONObject address = new JSONObject(); address.put("country", "china"); address.put("province", "jiangsu"); person.put("address", address); person.put("married", false); } catch (JSONException ex) { throw new RuntimeException(ex); } 

getType 與 optType 的差別

getType 在無法轉換或沒有值時會拋出 JSONException;optType 則是轉換失敗時回傳預設值,不會拋異常:

 try { phone.getLong(0); person.getLong("name"); // 會拋異常,因為名字無法轉為 long phone.optLong(0); // 內建默認值 phone.optLong(0, 1000); // 使用者提供的默認值 person.optLong("name"); person.optLong("name", 1000); // 不拋異常,而是回傳 1000 } catch (JSONException ex) { } 

用 JSONStringer 建立 JSON

注意 object/endObject、array/endArray 必須成對使用:

 try { JSONStringer jsonText = new JSONStringer(); jsonText.object(); jsonText.key("phone"); jsonText.array(); jsonText.value("12345678").value("87654321"); jsonText.endArray(); jsonText.key("name"); jsonText.value("yuanzhifei89"); jsonText.key("age"); jsonText.value(100); jsonText.key("address"); jsonText.object(); jsonText.key("country"); jsonText.value("china"); jsonText.key("province"); jsonText.value("jiangsu"); jsonText.endObject(); jsonText.key("married"); jsonText.value(false); jsonText.endObject(); } catch (JSONException ex) { throw new RuntimeException(ex); } 

用 JSONTokener 解析 JSON

把 JSON 文字解析成物件,只需 nextValue 一個方法即可:

 private static final String JSON = "{" + " \"phone\" : [\"12345678\", \"87654321\"]," + " \"name\" : \"yuanzhifei89\"," + " \"age\" : 100," + " \"address\" : { \"country\" : \"china\", \"province\" : \"jiangsu\" }," + " \"married\" : false," + "}"; try { JSONTokener jsonParser = new JSONTokener(JSON); JSONObject person = (JSONObject) jsonParser.nextValue(); person.getJSONArray("phone"); person.getString("name"); person.getInt("age"); person.getJSONObject("address"); person.getBoolean("married"); } catch (JSONException ex) { } 

JSONTokener 還有 next、nextClean、nextString、nextTo、back、skipPast、skipTo 等方法,可用來逐字巡覽 JSON 文字。

標準的 JSON 請求流程

 HttpPost request = new HttpPost(url); JSONObject param = new JSONObject(); param.put("name", "rarnu"); param.put("password", "123456"); StringEntity se = new StringEntity(param.toString()); request.setEntity(se); HttpResponse httpResponse = new DefaultHttpClient().execute(request); String retSrc = EntityUtils.toString(httpResponse.getEntity()); JSONObject result = new JSONObject(retSrc); String token = result.get("token"); 

完整範例:解析單筆與多筆資料

以下範例示範如何從伺服器取得 JSON,並分別解析單筆歌手資料與多筆歌手清單:

 public class JsonActivity extends Activity { private TextView tvJson; private Button btnJson; private Button btnJsonMulti; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tvJson = (TextView) this.findViewById(R.id.tvJson); btnJson = (Button) this.findViewById(R.id.btnJson); btnJsonMulti = (Button) this.findViewById(R.id.btnJsonMulti); btnJson.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String strUrl = ServerPageUtil.getStrUrl(UrlsOfServer.JSON_SINGER); String strResult = connServerForResult(strUrl); parseJson(strResult); } }); btnJsonMulti.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String strUrl = ServerPageUtil.getStrUrl(UrlsOfServer.JSON_SINGERS); String strResult = connServerForResult(strUrl); parseJsonMulti(strResult); } }); } private String connServerForResult(String strUrl) { HttpGet httpRequest = new HttpGet(strUrl); String strResult = ""; try { HttpClient httpClient = new DefaultHttpClient(); HttpResponse httpResponse = httpClient.execute(httpRequest); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { strResult = EntityUtils.toString(httpResponse.getEntity()); } } catch (ClientProtocolException e) { tvJson.setText("protocol error"); e.printStackTrace(); } catch (IOException e) { tvJson.setText("IO error"); e.printStackTrace(); } return strResult; } private void parseJson(String strResult) { try { JSONObject jsonObj = new JSONObject(strResult).getJSONObject("singer"); int id = jsonObj.getInt("id"); String name = jsonObj.getString("name"); String gender = jsonObj.getString("gender"); tvJson.setText("ID號"+id + ", 姓名:" + name + ",性別:" + gender); } catch (JSONException e) { e.printStackTrace(); } } private void parseJsonMulti(String strResult) { try { JSONArray jsonObjs = new JSONObject(strResult).getJSONArray("singers"); String s = ""; for(int i = 0; i < jsonObjs.length() ; i++){ JSONObject jsonObj = ((JSONObject)jsonObjs.opt(i)).getJSONObject("singer"); int id = jsonObj.getInt("id"); String name = jsonObj.getString("name"); String gender = jsonObj.getString("gender"); s += "ID號"+id + ", 姓名:" + name + ",性別:" + gender+ "\n" ; } tvJson.setText(s); } catch (JSONException e) { e.printStackTrace(); } } } 

掌握 JSONObject、JSONArray 與 JSONTokener 這三個核心類別,你就能應付絕大多數的 JSON 解析場景了。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved