編輯:Android 開發實例
行動裝置上的資料多半來自遠端 API,而 JSON 正是這些回應最常見的樣貌。相比 XML,它少了標籤的冗餘,寫起來省事、讀起來清楚,解析速度也更快。本章要帶你看懂一份 JSON 的結構,並用 Android 內建的類別把值取出來。
Android 內建的 JSON 工具共有四個:JSONArray(陣列)、JSONObject(物件)、JSONStringer(組字串用)與 JSONTokenizer(逐段解析用)。實務上八九成的需求,前兩個就足夠應付。
先決定你要什麼。以下這段天氣資料中,我們鎖定的是溫度:
{ "sys": { "country":"GB", "sunrise":1381107633, "sunset":1381149604 }, "weather":[ { "id":711, "main":"Smoke", "description":"smoke", "icon":"50n" } ], "main": { "temp":304.15, "pressure":1009, } }
| 編號 | 元素與說明 |
|---|---|
| 1 | Array([]) 用方括號包起來的是陣列,裡頭的每個項目都有順序。 |
| 2 | Object({}) 用大括號包起來的是物件,由一組組鍵值對構成。 |
| 3 | Key 鍵一定是字串;鍵與值配對,才形成一個完整的物件。 |
| 4 | Value 值可以是字串、整數、浮點數、布林,也可以是巢狀的物件或陣列。 |
從上面的例子可以看到:sys 與 main 是巢狀物件,weather 則是物件陣列——想取出天氣描述,得先進陣列再進物件。
先把整段文字包成 JSONObject:
String in; JSONObject reader = new JSONObject(in);
再逐層深入,用對應型別的方法取出每個鍵的值:
JSONObject sys = reader.getJSONObject("sys"); country = sys.getString("country"); JSONObject main = reader.getJSONObject("main"); temperature = main.getString("temp");
還有這些方法可以搭配使用:
| 編號 | 方法與說明 |
|---|---|
| 1 | get(String name) 以 Object 型別回傳,需自行轉型。 |
| 2 | getBoolean(String name) 回傳布林值。 |
| 3 | getDouble(String name) 回傳 double 數值。 |
| 4 | getInt(String name) 回傳整數。 |
| 5 | getLong(String name) 回傳 long 數值。 |
| 6 | length() 回傳鍵值對的數量。 |
| 7 | names() 回傳所有鍵名稱組成的陣列。 |
如果欄位可能不存在,改用 optString()、optInt() 這類 opt 系列方法會更保險,它們在找不到鍵時回傳預設值而不丟例外。
接下來把這些片段組裝成一個真正會連網的程式:輸入城市、按下按鈕、取得 JSON 並解析顯示。
| 步驟 | 做法 |
|---|---|
| 1 | 以 Android Studio 建立專案 JSONParser,Target SDK 與編譯版本請取最新。 |
| 2 | 於 src/MainActivity.java 補上程式碼。 |
| 3 | 於 res/layout/activity_main.xml 加入元件。 |
| 4 | 於 res/values/string.xml 加入字串。 |
| 5 | 新增 src/HandleJSON.java 負責抓取與解析。 |
| 6 | 於 AndroidManifest.xml 加上 INTERNET 權限。 |
| 7 | 執行、安裝並驗證。 |
主活動:
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()); } }
網路與解析:
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() : ""; } }
版面:
<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/textViem2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView1" android:layout_below="@+id/textViem1" 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/textViem2" 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/textViem3" android:layout_below="@+id/textViem3" android:layout_marginTop="32dp" android:text="@string/humidity" android:textAppearance="?android:attr/textAppearanceSmall" /> <TextView android:id="@+id/textViem5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textViem4" android:layout_below="@+id/textViem4" 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/textViem3" android:layout_toRightOf="@+id/textViem3" android:ems="10" > <requestFocus /> </EditText> <EditText android:id="@+id/editText3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/textViem3" android:layout_alignBottom="@+id/textViem3" 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/textViem5" 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/textViem5" android:layout_alignBottom="@+id/textViem5" 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>
字串與權限:
<?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>
<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>
執行後的初始畫面:
在位置欄位填入城市(示範用紐約),按下 weather:
程式會連上 API、下載 JSON 並解析,把國碼、溫度、濕度與氣壓填進各欄位。
兩個實務提醒:一是回傳的溫度是開爾文,要轉攝氏需減 273.15;二是範例用 while(obj.parsingComplete); 空迴圈等待,會佔住主執行緒(UI 執行緒)造成 ANR,正式專案請改用非同步回呼或 LiveData 等機制,別把網路與等待放在主執行緒。
Android 登入畫面實作:含剩餘次數與鎖定機制
幾乎每個需要帳號的 App 都得面對同一個問題:怎麼做一個既好用又不容易被暴力嘗試的登入畫面。本章從最基礎的表單開始,逐步加上密碼遮罩與失敗次數限制。 第一步是兩個輸入
一支 App 多種語言:Android 本地化的資料夾命名規則與實作
App 上架之後,使用者可能來自任何國家。若介面只有單一語言,即便功能再好,也會在語言這一關流失不少潛在用戶。Android 的資源系統把這件事處理得非常優雅:你只要按命
Android Spinner 載入動畫:按鈕觸發與顯示控制
Spinner 是 Android 中常見的等待提示元件。當使用者觸發某個操作,但系統需要一點時間處理時,可以用轉圈動畫告知目前仍在進行中。 基本設定 在版面配置中加入
Android 進階:手機與 BLE 終端通信實戰
近來可穿戴設備發展火熱,也帶旺了相關技術,其中一項便是 BLE(Bluetooth Low Energy,低功耗藍牙)。BLE 是藍牙 4.0 的核心 Profile,主