編輯:Android 開發實例
行動裝置上的資料多半來自網路,而網路上的資料多半是 JSON。JSON 的全名是 JavaScript Object Notation,是一種不依附任何平台的純文字資料格式,語法簡單到用記事本都能讀懂,因此成為 XML 之外最普遍的中立交換格式。這一章帶你把「抓回字串 → 交給 JSONObject → 取出欄位」這條路走一遍。
Android 內建的 JSON 相關類別共有四個:JSONArray、JSONObject、JSONStringer、JSONTokenizer。日常開發真正會用到的是前兩個:物件用 JSONObject,清單用 JSONArray。
開始寫程式前,先確認要抓哪些欄位。以這段天氣 API 的示範回應為例,我們想要的是溫度:
{ "sys": { "country":"GB", "sunrise":1381107633, "sunset":1381149604 }, "weather":[ { "id":711, "main":"Smoke", "description":"smoke", "icon":"50n" } ], "main": { "temp":304.15, "pressure":1009, } }
符號看久了眼花,其實只要記住四種元素就夠:
| 編號 | 元素 | 說明 |
|---|---|---|
| 1 | 陣列 Array [] | 中括號代表一組清單,元素有順序,用索引取值,對應到 Java 就是 JSONArray。 |
| 2 | 物件 Object {} | 花括號代表一個鍵值集合,用名稱取值,對應到 Java 就是 JSONObject。 |
| 3 | 鍵 Key | 一定是用雙引號包住的字串,與其後的值配成一對。 |
| 4 | 值 Value | 可以是字串、數字、布林、null,也可以是另一個物件或陣列。 |
階段一,建立最外層的 JSONObject,把整段 JSON 文字餵進建構子:
String in; JSONObject reader = new JSONObject(in);
階段二,依層級逐個往下取。這份資料裡,國家碼在 sys 底下,溫度在 main 底下,所以要先取出子物件、再取值:
JSONObject sys = reader.getJSONObject("sys"); country = sys.getString("country"); JSONObject main = reader.getJSONObject("main"); temperature = main.getString("temp");
也就是說,getJSONObject() 用來往下鑽一層物件,getString() 用來把值取成字串。若某個鍵的值是清單,就換成 getJSONArray() 取得 JSONArray,再用 length() 與 getJSONObject(i) 遍歷。
這個類別還有其他 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() | 回傳包含所有鍵名稱的陣列。 |
一個實務建議:如果欄位有缺席的可能(例如某城市沒有回傳濕度),改用 optInt、optString 這類方法並帶入預設值,可以省下大量 try-catch。
下面這個 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,把網路連線與 JSON 解析獨立成一個類別。 |
| 6 | 編輯 AndroidManifest.xml,加上 INTERNET 權限。 |
| 7 | 編譯執行,在裝置上驗證。 |
主活動 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/textVew2" 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/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/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/textVew4" 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/textView5" android:layout_alignBottom="@+id/textVew5" 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 並解析,再把結果填回各欄位。以紐約為例,回傳內容大致如下:
天氣 API 回傳的溫度數值
要注意這個溫度是開爾文,想轉成攝氏就減 273.15。另外,範例中 while(obj.parsingComplete); 這種忙等寫法會把主執行緒卡死,正式專案請改用非同步回呼(AsyncTask、Volley、Retrofit 或協程),並在解析前先檢查 HTTP 狀態碼與 cod 欄位,避免把錯誤訊息當成正常資料來解析。
Android JSON 解析實作:用 JSONObject 取得天氣資料
從網路取得 JSON在 Android 應用中,JSON 常用來承載 API 回傳的資料。解析時,通常先取得完整字串,再建立 JSONObject,逐一讀取需要的欄位。解
Android Matrix 圖像變換完全解析:平移、旋轉、鏡像、錯切與復合變換
線性代數裡學過矩陣,但真正把矩陣用來做圖像變換,往往是在實際項目中才想通。這篇把 android.graphics.Matrix 的理論與用法系統梳理一遍。 一、3×3
Android 登入畫面實作:從輸入欄位到錯誤次數鎖定
這個題目要解決什麼 只要 App 需要帳號,就一定會有一塊登入介面:使用者輸入帳號與密碼,按下按鈕,由程式決定放行或退回。Facebook、微博這類服務是這樣,自家開發的
Android JSON 解析入門:JSONArray 與 JSONObject 的分工
JSON 是 JavaScript Object Notation 的縮寫,但它其實一點也不專屬於 JavaScript。因為語法極簡、幾乎所有語言都支援,它變成了跨平台