編輯:Android 開發實例
JSON(JavaScript Object Notation,JavaScript 物件符號法)是一種以純文字描述的資料交換格式。因為語法輕巧、人眼可讀,而且天生就能對應到多數程式語言的資料結構,它早已取代 XML,成為後端服務與用戶端之間最常見的溝通語言。本章要談的就是:在 Android 專案裡,如何把一段 JSON 字串還原成物件,並精準取出你真正需要的那幾個欄位。
Android 平台內建了四個處理 JSON 的類別:JSONArray、JSONObject、JSONStringer 與 JSONTokenizer。實務上最常打交道的是前兩者——JSONObject 負責花括號構成的鍵值結構,JSONArray 則負責中括號構成的有序清單。
解析的第一步其實不是寫程式,而是先想清楚要什麼。以下這段資料模擬一個天氣服務的回應,我們感興趣的是其中的溫度:
{ "sys": { "country":"GB", "sunrise":1381107633, "sunset":1381149604 }, "weather":[ { "id":711, "main":"Smoke", "description":"smoke", "icon":"50n" } ], "main": { "temp":304.15, "pressure":1009, } }
乍看是一團符號,其實結構相當規律。下表整理了一份 JSON 文件中會出現的四類元素:
| 編號 | 元素 | 說明 |
|---|---|---|
| 1 | 陣列 Array([]) | 中括號代表 JSON 陣列,用來盛放一組同類資料,例如上例中的 weather。 |
| 2 | 物件 Object({}) | 花括號代表 JSON 物件,是整份文件最基本的容器。 |
| 3 | 鍵 Key | 物件中的每一個名稱都是字串,鍵與值配對之後才構成一個完整的屬性。 |
| 4 | 值 Value | 對應鍵的內容,可能是字串、整數、浮點數、布林值,甚至又是一個物件或陣列。 |
要解析一份 JSON,先把整段文字交給 JSONObject 的建構子,讓它成為第一層的物件。寫法如下:
String in; JSONObject reader = new JSONObject(in);
接著才是逐層往下取值。JSON 的層級結構決定了取值順序:JSONObject 提供的方法負責把某一層的鍵拆成物件或基本型別,因此像溫度這種埋在 main 底下的欄位,就得先取得 main 再取 temp:
JSONObject sys = reader.getJSONObject("sys"); country = sys.getString("country"); JSONObject main = reader.getJSONObject("main"); temperature = main.getString("temp");
getJSONObject 會把指定鍵的內容當成 another JSON 物件回傳;getString 則是把指定鍵的內容當成字串回傳。除了這兩個,JSONObject 還準備了一整組 getter,可依欄位的實際型別挑著用:
| 編號 | 方法 | 說明 |
|---|---|---|
| 1 | get(String name) | 回傳該鍵的值,型別維持為 Object,需要自行轉型。 |
| 2 | getBoolean(String name) | 回傳該鍵的布林值。 |
| 3 | getDouble(String name) | 回傳該鍵的雙精度浮點數。 |
| 4 | getInt(String name) | 回傳該鍵的整數。 |
| 5 | getLong(String name) | 回傳該鍵的長整數。 |
| 6 | length() | 回傳這個物件所含鍵值對的數量。 |
| 7 | names() | 回傳一個陣列,內容是這個物件所有的鍵名稱。 |
若欄位可能不存在,改用一組 optXxx 系列方法會更保險,它們在找不到鍵時會回傳預設值而不丟例外。
下面用 JSONObject 做一個小工具:使用者輸入城市名稱,程式呼叫天氣 API 取得 JSON,解析後把國家、溫度、濕度與氣壓顯示在畫面上。範例可在實機或模擬器上執行。
| 步驟 | 做法 |
|---|---|
| 1 | 用 Android Studio 建立專案,命名為 JSONParser。建立時把 Target SDK 與 Compile With 對到最新版的 Android SDK,以便使用較新的 API。 |
| 2 | 修改 src/MainActivity.java,加入主要流程與事件處理程式碼。 |
| 3 | 修改 res/layout/activity_main.xml,補上輸入框、送出按鈕與結果欄位。 |
| 4 | 修改 res/values/string.xml,把畫面上用到的字串抽出來。 |
| 5 | 新增 src/HandleJSON.java,專門負責連線取回資料並解析 JSON。 |
| 6 | 修改 AndroidManifest.xml,加上上網權限。 |
| 7 | 執行 App,在裝置上驗證結果。 |
主活動的內容如下,檔案位置 src/com.yiibai.jsonparser/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) { // Inflate the menu; this adds items //to the action bar if it is present. 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()); } }
負責連線與解析的 src/com.yiibai.jsonparser/HandleJSON.java:
package com.example.jsonparser; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.json.JSONObject; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserFactory; 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) { // TODO Auto-generated catch block 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 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); // Starts the query 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:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginTop="15dp" android:text="@string/location" android:textAppearance="?android:attr/textAppearanceMedium" /> <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/textView1" android:layout_alignParentRight="true" android:ems="10" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView1" android:layout_below="@+id/textView1" android:layout_marginTop="68dp" android:text="@string/country" android:textAppearance="?android:attr/textAppearanceSmall" /> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textView2" android:layout_marginTop="19dp" android:text="@string/temperature" android:textAppearance="?android:attr/textAppearanceSmall" /> <TextView android:id="@+id/textView4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView3" android:layout_below="@+id/textView3" android:layout_marginTop="32dp" android:text="@string/humidity" android:textAppearance="?android:attr/textAppearanceSmall" /> <TextView android:id="@+id/textView5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView4" android:layout_below="@+id/textView4" android:layout_marginTop="21dp" android:text="@string/pressure" android:textAppearance="?android:attr/textAppearanceSmall" /> <EditText android:id="@+id/editText2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/textView3" android:layout_toRightOf="@+id/textView3" android:ems="10" > <requestFocus /> </EditText> <EditText android:id="@+id/editText3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/textView3" android:layout_alignBottom="@+id/textView3" android:layout_alignLeft="@+id/editText2" android:ems="10" /> <EditText android:id="@+id/editText4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/textView5" android:layout_alignLeft="@+id/editText1" android:ems="10" /> <EditText android:id="@+id/editText5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/testView5" android:layout_alignBottom="@+id/textView5" android:layout_alignRight="@+id/editText4" android:ems="10" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/editText2" android:layout_below="@+id/editText1" 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="action_settings">Settings</string> <string name="hello_world">Hello world!</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 權限,否則連線會直接被系統擋下:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.yiibai.jsonparser" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.yiibai.jsonparser.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 裝到 AVD 或實機上啟動,若各項設定都正確,會看到這樣的初始畫面:
在位置欄位輸入任一座城市,這裡示範紐約,然後按下 Weather 按鈕:
按下按鈕後,程式會連上線上 API 抓回 JSON 並解析。以紐約為例,回傳的內容大致如下:
Google 天氣 API 回傳的溫度數值
要留意的是,這個溫度使用的是開爾文(Kelvin)溫標。若想轉成比較直覺的攝氏度,減去 273.15 即可。
另外提醒一個實務上的重點:Android 4.0 之後已禁止在主執行緒(UI Thread)進行網路連線,所以正式專案請改用 AsyncTask、執行緒池或 Kotlin 協程來抓取資料,再回到主執行緒更新畫面。
Android 登入範例:帳密欄位設計與錯誤嘗試管理
登入畫面存在的目的,是向使用者索取憑證以進入特定應用。這類需求很常見,例如要登入 Facebook、微博等服務。 本章說明如何建立一個登入介面,以及如何處理安全性與錯誤嘗
Android 中的 SAX 解析:事件驅動的 XML 讀寫實作
Android 上處理 XML 有兩條路:DOM 與 SAX。DOM 會把整份文件讀進記憶體再操作,方便隨意跳轉查詢,但記憶體開銷大;SAX 則是事件驅動,解析器一邊讀一
把網頁連同圖片一起保存到本地的實現方案
做離線閱讀功能時,會遇到一個不算難但很瑣碎的需求:把一個帶圖片的網頁下載到本地,並讓它在沒有網絡時也能正常顯示。難點不在保存 HTML,而在於把裡面的圖片鏈路一併改成本地
封裝 SQLite 分頁表格控件 GVTable:表格區與分頁列的完整實作
前一篇談了 SQLite 的分頁讀取,但那個版本只是把資料印在文字方塊裡。這次往前一步:把「分頁 + 表格呈現」封裝成一個可重複使用的自訂控件。 執行結果: 為什