編輯:Android 開發實例
JSON(JavaScript Object Notation)是一種不依附任何程式語言的純文字資料格式。它不像 XML 需要層層疊疊的標籤與屬性宣告,因此在行動網路上傳得更快、解析也更省資源,早已成為 HTTP API 事實上的標準回應格式。本章要處理的問題很實際:拿到一段 JSON 字串之後,怎麼在 Android 裡把它變成物件,並精準取出需要的欄位。
Android SDK 內建四個與 JSON 有關的類別:JSONObject 代表大括號圍起的物件、JSONArray 代表方括號圍起的陣列、JSONStringer 以串流方式產生合法 JSON、JSONTokenizer 負責把字串切成 token 逐段讀。日常開發真正高頻使用的,其實只有前兩個。
解析之前,得先看清資料的形狀。以下是一段典型的天氣資料,而我們關心的其實只有國家代碼與溫度:
{ "sys": { "country":"GB", "sunrise":1381107633, "sunset":1381149604 }, "weather":[ { "id":711, "main":"Smoke", "description":"smoke", "icon":"50n" } ], "main": { "temp":304.15, "pressure":1009, } }
| 元素 | 說明 |
|---|---|
| Array([]) | 方括號代表陣列,裡頭可以放物件、字串或數字。 |
| Object({}) | 大括號代表物件,也就是 key/value 的集合。 |
| Key | 物件中的鍵,一定是字串,例如 "temp"。 |
| Value | 鍵所對應的值,可能是字串、整數、浮點數或布林值。 |
第一步,把整段文字交給 JSONObject 的建構子,取得最外層的根物件:
String in; JSONObject reader = new JSONObject(in);
第二步,逐層往下取值。物件裡包物件用 getJSONObject(),要字串就用 getString():
JSONObject sys = reader.getJSONObject("sys"); country = sys.getString("country"); JSONObject main = reader.getJSONObject("main"); temperature = main.getString("temp");
實務上還有一個小建議:如果欄位有可能缺席,改用 optJSONObject()、optString() 這類方法會更保險,它們找不到鍵時回傳 null 或你指定的預設值,而不是直接丟出例外。
| 方法 | 說明 |
|---|---|
| get(String name) | 取值並以 Object 型別回傳。 |
| getBoolean(String name) | 取得指定鍵的布林值。 |
| getDouble(String name) | 取得指定鍵的 double 值。 |
| getInt(String name) | 取得指定鍵的整數值。 |
| getLong(String name) | 取得指定鍵的 long 值。 |
| length() | 回傳這個物件裡 key/value 對的數量。 |
| names() | 回傳包含所有鍵名稱的字串陣列。 |
下面的範例把整個流程串起來:使用者輸入城市,App 發出請求、取得 JSON、解析,再把國家、溫度、濕度、氣壓填回畫面。
| 步驟 | 要做的事 |
|---|---|
| 1 | 用 Android Studio 建立專案,命名為 JSONParser,Target SDK 與 Compile With 都選新版 SDK。 |
| 2 | 修改 MainActivity.java,加入控制項宣告與 open() 事件。 |
| 3 | 在 activity_main.xml 排出五組標籤與輸入框,加上查詢按鈕。 |
| 4 | 在 res/values/string.xml 補上所有字串。 |
| 5 | 新增 HandleJSON.java,負責連線與解析。 |
| 6 | 在 AndroidManifest.xml 註冊 INTERNET 權限。 |
| 7 | 執行 App,在裝置上驗證結果。 |
MainActivity.java:
package com.example.jsonparser; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.widget.EditText; public class MainActivity extends Activity { private String url1 = "https://api.openweathermap.org/data/2.5/weather?q="; private EditText location,country,temperature,humidity,pressure; private HandleJSON obj; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); location = (EditText)findViewById(R.id.editText1); country = (EditText)findViewById(R.id.editText2); temperature = (EditText)findViewById(R.id.editText3); humidity = (EditText)findViewById(R.id.editText4); pressure = (EditText)findViewById(R.id.editText5); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } public void open(View view){ String url = location.getText().toString(); String finalUrl = url1 + url; country.setText(finalUrl); obj = new HandleJSON(finalUrl); obj.fetchJSON(); while(obj.parsingComplete); country.setText(obj.getCountry()); temperature.setText(obj.getTemperature()); humidity.setText(obj.getHumidity()); pressure.setText(obj.getPressure()); } }
HandleJSON.java 負責在背景執行緒連線,再把資料解析成欄位:
package com.example.jsonparser; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import org.json.JSONObject; import android.annotation.SuppressLint; public class HandleJSON { private String country = "county"; private String temperature = "temperature"; private String humidity = "humidity"; private String pressure = "pressure"; private String urlString = null; public volatile boolean parsingComplete = true; public HandleJSON(String url){ this.urlString = url; } public String getCountry(){ return country; } public String getTemperature(){ return temperature; } public String getHumidity(){ return humidity; } public String getPressure(){ return pressure; } @SuppressLint("NewApi") public void readAndParseJSON(String in) { try { JSONObject reader = new JSONObject(in); JSONObject sys = reader.getJSONObject("sys"); country = sys.getString("country"); JSONObject main = reader.getJSONObject("main"); temperature = main.getString("temp"); pressure = main.getString("pressure"); humidity = main.getString("humidity"); parsingComplete = false; } catch (Exception e) { e.printStackTrace(); } } public void fetchJSON(){ Thread thread = new Thread(new Runnable(){ @Override public void run() { try { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.connect(); InputStream stream = conn.getInputStream(); String data = convertStreamToString(stream); readAndParseJSON(data); stream.close(); } catch (Exception e) { e.printStackTrace(); } } }); thread.start(); } static String convertStreamToString(java.io.InputStream is) { java.util.Scanner s = new java.util.Scanner(is).useDelimiter("A"); return s.hasNext() ? s.next() : ""; } }
版面檔 res/layout/activity_main.xml(為了聚焦主題,這裡省略 margin、textAppearance 等純樣式屬性):
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/textView1" android:text="@string/location" /> <EditText android:id="@+id/editText1" android:layout_toRightOf="@id/textView1" /> <TextView android:id="@+id/textV2" android:text="@string/country" android:layout_below="@id/editText1" /> <EditText android:id="@+id/editText2" android:layout_below="@id/editText1" /> <TextView android:id="@+id/textView3" android:text="@string/temperature" android:layout_below="@id/editText2" /> <EditText android:id="@+id/editText3" android:layout_below="@id/editText2" /> <TextView android:id="@+id/textV4" android:text="@string/humidity" android:layout_below="@id/editText3" /> <EditText android:id="@+id/editText4" android:layout_below="@id/editText3" /> <TextView android:id="@+id/textV5" android:text="@string/pressure" android:layout_below="@id/editText4" /> <EditText android:id="@+id/editText5" android:layout_below="@id/editText4" /> <Button android:id="@+id/button1" android:onClick="open" android:text="@string/weather" /> </RelativeLayout>
res/values/string.xml:
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">JSONParser</string> <string name="location">Location</string> <string name="country">Country:</string> <string name="temperature">Temperature:</string> <string name="humidity">Humidity:</string> <string name="pressure">Pressure:</string> <string name="weather">Weather</string> </resources>
最後別忘了在 AndroidManifest.xml 加上 INTERNET 權限,少了這一行,連線會在執行階段直接被拒:
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.yiibai.jsonparser"> <uses-permission android:name="android.permission.INTERNET"/> <application android:label="@string/app_name" android:theme="@style/AppTheme"> <activity android:name=".MainActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
把 App 裝到模擬器或真機上啟動,設定無誤就會看到這樣的畫面:
接著在位置欄位輸入任一座城市,這裡以紐約為例:
按下 weather,App 便會向天氣服務要來 JSON 並解析。要留意的是,回傳的溫度是開爾文(K),想轉成比較直覺的攝氏度,減掉 273.15 即可。
Android 網路請求與圖片快取框架 enif 深入解析
enif 是一套針對早期 Android 應用設計的輕量框架,主要解決兩個常見問題:網路請求的統一管理,以及列表圖片載入時的快取與記憶體控制。它將底層連線、非同步任務、監
Android Loading Spinner 實作流程與除錯筆記
轉圈的載入動畫是使用者最熟悉的「請稍候」符號。它不需要你計算進度,只要如實傳達一件事:App 正在工作。Android 把這個元件做成 ProgressBar 的一種樣式
用 JSONObject 解析天氣 API 回傳的 JSON 資料
行動 App 的資料大多來自遠端伺服器,而 JSON 是目前最主流的傳輸格式。它的名稱源自 JavaScript Object Notation,但格式本身與語言無關,任
Android 登入畫面教學:帳密欄位設計與三次錯誤後鎖定的實作
登入畫面是使用者進入 Facebook、微博這類服務前的第一道門。它要收集一組憑證,驗證通過就放行。聽起來平凡,但實作時有三個細節決定成品是否堪用:密碼欄有沒有遮好、錯誤