編輯:Android 開發實例
JSON(JavaScript Object Notation,JavaScript 物件符號法)是一種以純文字為基礎、與程式語言無關的資料交換格式。因為結構輕量、可讀性高,而且幾乎所有語言都內建支援,它早已是 XML 之外最主流的選擇,也是行動裝置與伺服器溝通時最常見的資料格式。
本章要說明的是:在 Android 上如何把一段 JSON 文字還原成物件、如何逐層取出真正需要的欄位,最後用一個查詢天氣的小專案把整個流程跑完。
Android SDK 內建了 org.json 套件,其中四個類別各有分工:
多數情況下,只要用到 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,
"humidity": 78
}
}
| 項目 | 說明 |
|---|---|
Array([ ]) | 中括號代表一個 JSON 陣列,裡面的元素有順序,通常元素型態一致。 |
Object({ }) | 大括號代表一個 JSON 物件,是「鍵/值」對的集合。 |
| Key(鍵) | 物件中的每一筆資料都有一個字串型態的鍵,成對的鍵與值共同構成一個物件。 |
| Value(值) | 鍵對應的值可以是字串、整數、浮點數、布林值,也可以是另一個物件或陣列。 |
第一步是建立 JSONObject 實體,並把含有 JSON 內容的字串交給它:
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() 用來取出指定鍵底下的子物件;getString() 則是把指定鍵的值以字串形式取回。
| 方法 | 說明 |
|---|---|
get(String name) | 取得指定鍵的值,但回傳型別是通用的 Object。 |
getBoolean(String name) | 取得指定鍵的布林值。 |
getDouble(String name) | 取得指定鍵的 double 數值。 |
getInt(String name) | 取得指定鍵的整數值。 |
getLong(String name) | 取得指定鍵的 long 數值。 |
length() | 回傳這個物件中鍵值對的數量。 |
names() | 回傳一個陣列,內容是這個物件所有的鍵名稱。 |
實務上還有一組「容錯版」方法值得記住:optString()、optInt()、optJSONObject() 等,當鍵不存在時會回傳預設值而不丟出例外,能讓程式在面對不完整的 API 回應時更穩健。
接下來用 JSONObject 做一個小工具:使用者輸入城市名稱,按下按鈕後 App 連線到天氣服務取得 JSON,解析後把國家、溫度、濕度與氣壓顯示在畫面上。
這個範例需要連網,因此建議在實機上測試;若使用模擬器,也請確認網路連線正常。
| 步驟 | 做法 |
|---|---|
| 1 | 用 Android Studio 建立專案,命名為 JSONParser;建立時把 Target SDK 與 Compile With 設為較新的 Android SDK 版本,以便使用較新的 API。 |
| 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,選擇要安裝的裝置並驗證結果。 |
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;
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());
}
}
package com.example.jsonparser;
import java.io.InputStream;
import java.util.Scanner;
import javax.net.ssl.HttpsURLConnection;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import java.net.URL;
public class HandleJSON {
private String country = "country";
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);
java.net.HttpURLConnection conn =
(java.net.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(InputStream is) {
Scanner s = new Scanner(is).useDelimiter("A");
return s.hasNext() ? s.next() : "";
}
}
這裡有兩個實務上的提醒:網路請求一定要放在背景執行緒,否則在較新的 Android 版本上會直接丟出 NetworkOnMainThreadException;而範例中 while (obj.parsingComplete); 這種「忙等」寫法只是為了教學上簡單,正式專案建議改用 AsyncTask、Thread 加回呼,或 Kotlin 的協程來處理執行緒切換。
<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/textV8iew2"
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/textV8iew2"
android:ems="10" >
<requestFocus />
</EditText>
<EditText android:id="@+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textV8iew3"
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/textV8iew5"
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>
<?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>
<?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>
别忘了 <uses-permission android:name="android.permission.INTERNET" /> 這一行。少了它,App 在連線時會直接收到權限相關的例外,畫面上永遠看不到任何資料。
把 App 裝到模擬器或實機上啟動,若環境設定都正確,會看到如下的初始畫面:
接著在位置欄位輸入任一座城市,這裡以紐約為例,按下「Weather」按鈕:
按下按鈕後,App 會連線到天氣服務、下載對應的 JSON 並解析,再把欄位填回畫面。
天氣服務回傳的 temp 預設是「開爾文」,不是攝氏也不是華氏。若想顯示成比較直覺的攝氏度,可以用 攝氏 = 開爾文 − 273.15 換算,或在請求時帶上 units=metric 參數讓服務端直接回傳攝氏值。
Android 載入 Spinner:實作不確定模式的進度提示
在 Android 裡要讓使用者知道「系統正在忙」,最直接的方式就是拉一個進度條出來。進度條大致分成兩種形態:一種是進度明碼標示的 Loading Bar,另一種則是只轉
Android記事本範例剖析(一):入口、清單與 Intent 匹配機制
這是 Android 記事本範例系列的第一篇。與其直接背誦 API,不如從一個完整的小程式開始,觀察入口、列表、Intent 與 ContentProvider 如何串起
Android手機衛士(十六):事件傳遞與 CheckBox 點擊衝突
當點擊 SettingItemView 時,事件會由父層配置接收,再傳遞給自訂元件。若點擊位置在 CheckBox,事件可能被 CheckBox 消耗,導致自訂元件無法更
Android 程式使用自訂字庫的方法與注意事項
在 Android 系統下,TextView 對字體的支援其實相當有限。預設情況下,TextView 的 typeface 屬性只支援 Sans、serif、monosp