編輯:Android 開發實例
JSON 代表 JavaScript Object Notation,是一種獨立的資料交換格式,也是 XML 的最佳替代品。本章說明如何解析 JSON 檔案,並從中取出需要的資訊。
Android 提供了四個不同的類別來處理 JSON 資料,分別是 JSONArray、JSONObject、JSONStringer 與 JSONTokenizer。
第一步是找出你感興趣的 JSON 欄位。例如下面這段 JSON 中,我們感興趣的資料是溫度:
{ "sys": { "country":"GB", "sunrise":1381107633, "sunset":1381149604 }, "weather":[ { "id":711, "main":"Smoke", "description":"smoke", "icon":"50n" } ], "main": { "temp":304.15, "pressure":1009, } }
JSON 檔案包含許多元件。下表定義了 JSON 檔案的組成元素及其說明:
1. Array([):在 JSON 檔案中,方括號([])代表 JSON 陣列。
2. Objects({):在 JSON 檔案中,大括號({)代表 JSON 物件。
3. Key:JSON 物件中包含一個鍵,它是字串。鍵/值對組成了 JSON 物件。
4. Value:每個鍵對應的值,可能是字串、整數或 double 等。
要解析 JSON 物件,我們會建立一個 JSONObject 物件,並把含有 JSON 資料的字串指定給它。語法如下:
String in; JSONObject reader = new JSONObject(in);
最後一步是解析 JSON。JSON 檔案由不同物件組成,各有不同的鍵/值對,因此 JSONObject 有一個獨立函式用於解析 JSON 檔案的每個組成部分。語法如下:
JSONObject sys = reader.getJSONObject("sys"); country = sys.getString("country"); JSONObject main = reader.getJSONObject("main"); temperature = main.getString("temp");
getJSONObject 會回傳 JSON 物件,getString 則回傳指定鍵的字串值。
除了這些方法,這個類別還提供了其他方法,能讓 JSON 檔案的解析更為完善:
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():回傳一個陣列,包含此物件的所有字串名稱。
這裡用一個範例示範如何使用 JSONObject 類別。它會建立一個基本的天氣應用程式,讓使用者能解析並顯示來自天氣 API 的 JSON 結果。
你可以在實際裝置或模擬器上執行來驗證這個範例。
實作步驟
1. 使用 Android Studio 建立 Android 應用程式,命名為 JSONParser。建立專案時,Target SDK 請編譯於最新版本的 Android SDK 並使用更高等級的 API。
2. 修改 src/MainActivity.java,加入必要程式碼。
3. 修改 res/layout/activity_main.xml,加入對應的 XML 元件。
4. 修改 res/values/string.xml,加入必要字串。
5. 在 src/ 下建立新的 Java 檔 HandleJSON.java,用來取得並解析資料。
6. 修改 AndroidManifest.xml,加入必要的網路權限。
7. 執行應用程式,選擇一部 Android 裝置安裝並驗證結果。
修改後的主活動檔案 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/text1" 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/text1" android:layout_alignParentRight="true" android:ems="10" /> <TextView android:id="@+id/text2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/text1" android:layout_below="@+id/text1" android:layout_marginTop="68dp" android:text="@string/country" android:textAppearance="?android:attr/textAppearanceSmall" /> <TextView android:id="@+id/text3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/text2" android:layout_marginTop="19dp" android:text="@string/temperature" android:textAppearance="?android:attr/textAppearanceSmall" /> <TextView android:id="@+id/text4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/text3" android:layout_below="@+id/text3" android:layout_marginTop="32dp" android:text="@string/humidity" android:textAppearance="?android:attr/textAppearanceSmall" /> <TextView android:id="@+id/text5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/text4" android:layout_below="@+id/text4" 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/text3" android:layout_toRightOf="@+id/text3" android:ems="10" > <requestFocus /> </EditText> <EditText android:id="@+id/editText3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/text3" android:layout_alignBottom="@+id/text3" 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/text5" 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/text5" android:layout_alignBottom="@+id/text5" 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>
接著來執行修改後的 JSONParser 應用程式。把程式安裝到 AVD 並啟動,如果一切設定與程式都沒有問題,會顯示下面的模擬器畫面:
現在需要做的是在位置欄位輸入任一個地點。舉例來說,我已經輸入了紐約。按下 weather 按鈕後,畫面會像下面這樣出現在 AVD 中:
按下 weather 按鈕時,應用程式會連上谷歌天氣 API,請求需要的 JSON 檔案並加以解析。如果輸入的是紐約,將會回傳對應的資料。
請注意,這個溫度是開爾文,所以如果你想把它轉換成更容易理解的格式,必須換算成攝氏度。
Android 自訂 ViewGroup 打造多風格 SlidingMenu
側滑選單是許多 App 常見的互動模式。本文以自訂 ViewGroup 的方式,從最基礎的側滑菜單開始,逐步加入 Scroller 自動吸附、事件攔截、滑動衝突處理,最後
在 Android 裡顯示「載入中」的轉圈動畫(ProgressBar Spinner)
使用者按下按鈕之後,若畫面毫無反應,通常不到兩秒就會開始懷疑是不是當機了。給他一個轉圈的載入動畫,是最便宜也最有效的解法。Android 把這個需求交給 Progress
Android 模擬位置的完整實現方法(支援 Android 6.0)
在開發與測試定位相關功能時,模擬位置是一項非常實用的技巧——它能讓你在沒有真正移動的情況下,測試各種經緯度下的應用表現。本文整理了支援 Android 6.0 的模擬位置
Android ProgressBar 教學:用 Spinner 提示背景工作
當 App 執行網路請求、讀取檔案或等待伺服器回應時,使用者需要知道目前有工作正在進行。Android 的 ProgressBar 可以分成兩種常見型態:進度條與 Spi