編輯:Android 開發實例
JSON 是 JavaScript Object Notation 的縮寫,但它其實一點也不專屬於 JavaScript。因為語法極簡、幾乎所有語言都支援,它變成了跨平台資料交換的通用語言,也是 XML 最常被替換掉的對象。對 Android 開發者來說,「把伺服器回傳的 JSON 變成 App 裡能用的物件」幾乎是必備技能。
Android SDK 內建四個 JSON 相關類別:JSONArray、JSONObject、JSONStringer 與 JSONTokenizer。其中 JSONArray 對應中括號組成的清單,JSONObject 對應花括號組成的鍵值結構,兩者可以互相嵌套,足以應付絕大多數的 API 回應。
正式解析之前,先確認目標。下面這段天氣資料裡,我們要抓的是溫度:
{ "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([]) | 中括號表示有序清單,取值時用索引,Java 端對應 JSONArray。 |
| 2 | 物件 Object({}) | 花括號表示鍵值集合,取值時用名稱,Java 端對應 JSONObject。 |
| 3 | 鍵 Key | 必須是置於雙引號中的字串,與其後的值構成一組屬性。 |
| 4 | 值 Value | 可以是字串、整數、浮點數、布林或 null,也可以是嵌套的物件與陣列。 |
第一步,用整段文字建立最外層的 JSONObject:
String in; JSONObject reader = new JSONObject(in);
第二步,按層級取用。這份資料中,country 藏在 sys 裡,temp 藏在 main 裡,所以要先取得子物件再取值:
JSONObject sys = reader.getJSONObject("sys"); country = sys.getString("country"); JSONObject main = reader.getJSONObject("main"); temperature = main.getString("temp");
換句話說,getJSONObject() 負責「往下鑽一層」,getString() 負責「把值取成字串」。如果目標是 weather 那類清單,就改用 getJSONArray("weather"),再用 length() 搭配 getJSONObject(i) 逐筆取出。
JSONObject 另外還備有這幾個方法,可依欄位型別選用:
| 編號 | 方法 | 說明 |
|---|---|---|
| 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() | 回傳一個陣列,內容是所有鍵的名稱。 |
接下來用 JSONObject 做一個天氣查詢 App:使用者輸入城市,程式抓回 JSON 解析後顯示國家、溫度、濕度與氣壓。可在實機或模擬器上執行。
| 步驟 | 做法 |
|---|---|
| 1 | 用 Android Studio 建立專案並命名為 JSONParser,Target SDK 與 Compile With 設為最新版 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 | 執行 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/textVew1" 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/textVew1" 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/textVew2" 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/textVew3" 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/textVew4" android:layout_below="@+id/textVew4" 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/textVew3" 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/textVew3" 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/textVew5" 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/textView5" 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:
<?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 並解析,把結果填回畫面。以紐約為例,回傳的資料大致如下:
天氣 API 回傳的溫度欄位
最後提醒兩件事。第一,回傳的溫度是開爾文,轉攝氏需減去 273.15。第二,範例中的忙等迴圈會阻塞主執行緒,正式專案請務必改用非同步機制(AsyncTask、Volley、Retrofit、Kotlin 協程等),並在解析前先確認 HTTP 狀態碼,避免把錯誤訊息誤當成正常資料。
Android 載入動畫怎麼做?ProgressBar 轉圈指示器完整說明
使用者按下一顆按鈕後若畫面毫無反應,通常會以為 App 當掉了。這時候一個小小的旋轉動畫,就能把「不確定要等多久」的焦慮大幅降低。Android 的 ProgressBa
AudioManager 實戰:用程式控制鈴聲模式與音量
想要讓 App 直接切換手機的鈴聲模式(正常、靜音、震動),Android 提供了 AudioManager 這個系統服務。本文示範如何取得它、切換模式、讀回目前狀態,並
Android 登入畫面實作:介面、驗證與失敗次數鎖定
幾乎每一款需要使用者帳號的應用——社群軟體、雲端服務、內部系統——都得面對同一個問題:怎麼設計一個既好用又安全的登入畫面。本章從版面配置一路做到「三次錯誤就鎖住登入鈕」的
Android記事本範例剖析(三):Activity生命週期與自訂控制項
本篇是 Android 記事本範例系列的第三篇,重點放在 Activity 生命週期與自訂控制項。透過實際切換畫面並觀察 Logcat,可以更清楚理解 Android 如