編輯:Android 開發實例
JSON 的全名是 JavaScript Object Notation(JavaScript 物件符號法),它最大的優點是輕量、易讀,而且天生就適合在瀏覽器與伺服器之間傳遞資料。相較於標籤冗長、解析成本高的 XML,JSON 早已成為今日行動應用與後端介面溝通的首選格式。本章要談的,就是當你的 Android App 從網路拿到一段 JSON 字串之後,該怎麼把它拆解成應用真正需要的欄位。
Android 平台內建了四個與 JSON 相關的類別:JSONObject、JSONArray、JSONStringer 與 JSONTokenizer。其中前兩者是日常開發最常打交道的角色——物件用大括號包起來,陣列用中括號包起來,層層嵌套之後,就是一份完整的資料結構。
動手解析之前,請先想清楚一件事:你真正需要哪些欄位? 以下面這段來自天氣服務的資料為例,我們感興趣的其實只有「溫度」,其他欄位可以先忽略:
{
"sys": {
"country": "GB",
"sunrise": 1381107633,
"sunset": 1381149604
},
"weather": [
{
"id": 711,
"main": "Smoke",
"description": "smoke",
"icon": "50n"
}
],
"main": {
"temp": 304.15,
"pressure": 1009
}
}
一份 JSON 文件其實只由幾種元素反覆組合而成,把它們記熟,之後看任何 API 回應都不會迷路:
| Sr.No | 元素 | 說明 |
|---|---|---|
| 1 | Array([) | 中括號代表 JSON 陣列,用來裝放多筆同類型的資料 |
| 2 | Object({) | 大括號代表 JSON 物件,是「鍵/值」成對出現的集合 |
| 3 | Key | 物件中的鍵一律是字串,每組鍵與值合起來構成一個屬性 |
| 4 | Value | 對應的值可以是字串、整數、浮點數、布林值,甚至又是另一個物件或陣列 |
解析的第一步,是把整段文字餵給 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");
簡單說,getJSONObject() 會回傳指定鍵底下那一層物件,而 getString() 則是直接取出該鍵對應的字串值。除了這兩個,JSONObject 還提供了更細緻的取值工具:
| Sr.No | 方法 | 說明 |
|---|---|---|
| 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:我們做一個簡易的天氣應用,讓使用者輸入城市名稱,App 呼叫天氣服務的 API、抓取 JSON、解析後把結果顯示在畫面上。你可以在實機或模擬器上執行。
| 步驟 | 說明 |
|---|---|
| 1 | 用 Android Studio 建立專案,命名為 JSONParser。建立時請把 Target SDK 對到 Android SDK 的最新版本,並使用較新的 API Level |
| 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,選擇要安裝的 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) {
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.InputStream;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import java.net.HttpURLConnection;
import java.net.URL;
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() : "";
}
}
版面配置檔 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/textVirew3"
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 註冊連網權限,否則請求會直接失敗:
<?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 上啟動,如果一切設定無誤,你會看到這樣的模擬器視窗:
接下來只要在 Location 欄位輸入任一座城市,這裡以紐約為例:
按下「weather」按鈕後,App 會向天氣服務的 API 送出請求、取回 JSON 並解析,最後把欄位填進畫面。若輸入的是紐約,服務端會回傳類似這樣的內容(London 範例):倫敦/谷歌天氣 API 溫度。
這裡有個容易踩到的坑:回傳的溫度是「克氏(Kelvin)」而非攝氏。如果你想顯示成比較直覺的 °C,記得自己做一次換算(攝氏 = 克氏 − 273.15)。
Android 本地化實作演練:從英文預設值到義大利文翻譯
把寫死的中文或英文字串丟進 App,短期很快,長期很痛。Android 早就提供了答案:所有顯示文字都放進資源檔,再依語言準備對應版本,系統會依裝置設定自動挑選。本章從建
以百度地圖 SDK 實現 Android 定位功能:完整流程解析
LBS 位置服務是 Android 應用中愈來愈常見的能力,從定位、地圖顯示到導航,都建立在它之上。本文以百度地圖定位 SDK 為例,逐步示範如何完成一次定位並把結果回傳
Android 檔案搜尋實作:在 SD 卡中遞迴查找指定檔名
做檔案管理器或需要掃描外部儲存空間時,「找出所有符合關鍵字的檔案」幾乎是必備功能。本文示範一個簡潔的實作:使用者輸入搜尋目錄與關鍵字,程式遞迴走訪底下所有子目錄,把命中的
Android AppWidgetProvider 的使用介紹
AppWidgetProvider 主要用於在桌面顯示插件。開發時通常需要準備一個 appwidget-provider 配置檔,用來宣告初始布局、最小寬高與更新週期,再