編輯:Android 開發實例
JSON 是 JavaScript Object Notation 的縮寫,作為一種輕量、語言中立的資料交換格式,它比 XML 更精簡、更容易閱讀,因此在 Android 開發中幾乎成了伺服器回傳資料的標準語言。本章要說明的是:拿到一段 JSON 字串之後,如何在應用程式裡把它拆解開來,準確取出感興趣的那幾個欄位。
Android SDK 內建了四個處理 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 陣列,用來承放一組同類型的物件。
2. 物件 Object({ }):大括號代表一個 JSON 物件。
3. 鍵 Key:物件中的每一組資料都以字串形式的鍵作為名稱,鍵與值配對之後才構成一個完整的物件。
4. 值 Value:對應每個鍵的內容,可能是字串、整數、浮點數、布林值,甚至又是一個物件或陣列。
解析的第一步,是把整段文字交給 JSONObject 的建構子,讓它變成一個可以查詢的物件:
String in; JSONObject reader = new JSONObject(in);
接著就能一層一層往下鑽。JSON 的結構往往嵌套著不同層級的物件,JSONObject 為每一種取值情境都準備了對應的方法:
JSONObject sys = reader.getJSONObject("sys"); country = sys.getString("country"); JSONObject main = reader.getJSONObject("main"); temperature = main.getString("temp");
這裡的 getJSONObject 會依鍵名回傳一個巢狀的 JSON 物件,而 getString 則回傳該鍵對應的字串值。
除此之外,JSONObject 還提供了這些方法,能讓解析工作更為靈活:
get(String name):以 Object 型別回傳指定鍵的值。
getBoolean(String name):回傳布林值。
getDouble(String name):回傳 double 數值。
getInt(String name):回傳整數。
getLong(String name):回傳 long 數值。
length():回傳這個物件裡鍵值對的數量。
names():回傳一個陣列,內容是此物件所有的鍵名稱。
下面的範例會實作一個簡易的天氣應用程式,讓使用者輸入城市名稱,程式呼叫天氣 API 取得 JSON 資料,解析後把結果顯示在畫面上。你可以在實機或模擬器中實際跑一次。
實作步驟
1. 用 Android Studio 建立專案,命名為 JSONParser,Target SDK 與 Compile With 請選擇最新版本的 Android SDK。
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/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,注意 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 回傳的溫度單位是 Kelvin(開爾文)。如果你想顯示成比較直覺的攝氏度,記得自己做一次單位換算。
Android ApiDemo 系列一:建立範例專案
Android SDK 內附的 ApiDemo 是學習 Android API 的重要資源。它把大量範例依功能分類,例如 App、Content、Graphics、Med
Android 編譯與運行過程深入分析
Android 應用從原始碼到 APK 的過程,包含資源編譯、Java 編譯、dex 轉換、打包與簽名等步驟。理解這些流程有助於排查建置問題。 資源與 R 檔案 aap
Android Spinner 載入提示:從使用者等待心理談 ProgressBar 的用法
當一個操作無法預估還要多久時,使用者需要的不是精確的百分比,而是一個持續存在的「我沒死掉」訊號。Android 把這件事交給 ProgressBar 的不確定模式,也就是
Android 進度指示:Spinner 轉圈圈怎麼用
當 App 要執行一段耗時的工作,使用者需要一個「你正在忙」的提示,這就是進度條存在的意義。Android 的進度條有兩種常見形態:一種是明確顯示百分比的橫向進度列,另一