編輯:Android 開發實例
JSON 是 JavaScript Object Notation 的縮寫,但今天的它早已與 JavaScript 脫鉤,成為一門語言中立的資料交換格式。相較於 XML,它沒有冗長的開始與結束標籤,同一份資料的體積小了許多,解析時也不必走 DOM 那套昂貴的樹狀建構,這正是它在行動裝置上特別受歡迎的原因。
本章從資料結構談起,一路做到一個能實際抓天氣資料的 App,並把解析過程中容易踩到的型別問題講清楚。
先確認你要的資料長什麼樣子。以下這段天氣回應中,我們真正需要的是 sys.country 與 main.temp:
{ "sys": { "country":"GB", "sunrise":1381107633, "sunset":1381149604 }, "weather":[ { "id":711, "main":"Smoke", "description":"smoke", "icon":"50n" } ], "main": { "temp":304.15, "pressure":1009, } }
| 元素 | 說明 |
|---|---|
| Array [] | 方括號代表陣列,weather 就是一個只有單一元素的陣列。 |
| Object {} | 大括號代表物件,sys 與 main 都是物件。 |
| Key | 物件中的鍵,固定為字串。 |
| 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");
這裡有個實務上的關鍵:getString() 拿數字其實是可以的,因為它會把值轉成字串回傳;但反過來用 getInt() 去取 "304.15" 這種帶小數的值就會出問題。所以取值前先想清楚該欄位的真實型別,或是直接用泛用的 get()、optString() 來避開型別例外。
| 方法 | 說明 |
|---|---|
| get(String name) | 以 Object 型別回傳值。 |
| getBoolean(String name) | 取得布林值。 |
| getDouble(String name) | 取得 double 值。 |
| getInt(String name) | 取得整數值。 |
| getLong(String name) | 取得 long 值。 |
| length() | 回傳 key/value 對的數量。 |
| names() | 回傳所有鍵名稱組成的陣列。 |
以下範例讓使用者輸入城市名稱,App 請求天氣服務、解析 JSON,再把結果填回畫面。網路工作被放在獨立執行緒中,避免佔用主執行緒而觸發 ANR。
| 步驟 | 要做的事 |
|---|---|
| 1 | 用 Android Studio 建立 JSONParser 專案,Target SDK 與 Compile With 都選新版。 |
| 2 | 修改 MainActivity.java,加入 open() 事件與畫面控制項。 |
| 3 | 修改 activity_main.xml 加入輸入欄與查詢鈕。 |
| 4 | 修改 res/values/string.xml 加入字串。 |
| 5 | 新增 HandleJSON.java,負責連線與解析。 |
| 6 | 在 AndroidManifest.xml 加上 INTERNET 權限。 |
| 7 | 執行並驗證。 |
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); } public void open(View view){ String url = location.getText().toString(); String finalUrl = url1 + url; 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 把「連線」與「解析」切成兩個方法,readAndParseJSON() 就是純解析邏輯:
package com.example.jsonparser; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import org.json.JSONObject; 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; } 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() : ""; } }
activity_main.xml(省略純樣式屬性,五組標籤與輸入框成對排列):
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/textV1" android:text="@string/location" /> <EditText android:id="@+id/editText1" android:layout_toRightOf="@id/textV1" /> <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/textV3" 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>
string.xml 與 AndroidManifest.xml:
<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> <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"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
啟動 App,畫面上是位置欄與四個結果欄:
輸入城市(範例使用紐約)後按下查詢:
App 會向天氣服務索取 JSON 並解析。要注意的是回傳的溫度單位是開爾文,想轉成攝氏度就減 273.15。另外,範例用的公開端點屬於教學性質,正式專案請改接你申請到的、且支援 HTTPS 的服務。
Android 進度提示:用 ProgressBar 做一個轉不停的小圈圈
當 App 要下載檔案、讀取資料庫或等待網路回應時,使用者需要一個「它還在動」的訊號,否則很容易以為程式當掉了。Android 的 ProgressBar 就是為這件事而
Android 加載 Spinner:用 ProgressBar 顯示不確定進度
在 Android 中,可以透過加載進度條來顯示任務的進展。進度條有兩種形狀:加載欄與加載微調(spinner)。本章我們將討論 spinner。 Spinner 用於顯
用 MediaPlayer 實作 Android 音樂播放器(含進度條與 ±5 秒跳轉)
要在 App 裡播放一段音樂,Android 給了你不少選擇,但最常被拿出來用的仍是 MediaPlayer。它把底層的播放服務包成一個好操作的物件,不論音樂是打包在 A
Android 控件封裝:把 Dialog 包成可重複使用的自定義元件
自定義 Dialog 幾乎每個專案都會寫,但每次都寫一遍實在混亂。與其反覆拼湊,不如一次封裝好,以後直接 copy 使用。 主 Activity public c