編輯:Android 開發實例
行動裝置上的資料多半來自遠端伺服器,而這些資料十之八九是以 JSON 形式送過來的。它之所以能取代 XML 成為主流,原因很實際:沒有冗餘標籤、體積小、人眼也看得懂。Android 從早期版本就內建了 JSON 的處理能力,寫起來相當輕量。
接下來用最精簡的方式,把「拿到字串 → 建立物件 → 逐層取值」這條路走一遍。
動手寫程式之前,先把回傳的資料攤開來看。以天氣服務為例,我們關心的是溫度:
{
"sys": { "country": "GB", "sunrise": 1381107633, "sunset": 1381149604 },
"weather": [ { "id": 711, "main": "Smoke", "description": "smoke", "icon": "50n" } ],
"main": { "temp": 304.15, "pressure": 1009 }
}
最外層是物件,sys 與 main 是嵌套的子物件,weather 則是物件組成的陣列。看懂這層關係,就知道哪些該用 getJSONObject()、哪些該用 getJSONArray()。
| 元素 | 說明 |
|---|---|
| Array([]) | 有序集合,元素以逗號分隔。 |
| Object({}) | 由多組鍵值交所構成的集合。 |
| Key | 物件的鍵,一律為字串。 |
| Value | 對應的值,型別可以是字串、整數、浮點數、布林或 null,也可以是子物件與陣列。 |
Android 的 org.json 套件裡有 JSONArray、JSONObject、JSONStringer、JSONTokenizer。讀取第三方 API 時,前兩個就足夠;JSONStringer 是反過來用來組 JSON 字串的;JSONTokenizer 則在需要逐段解析時才派得上用場。
把整段文字餵給 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() 這類方法則回傳指定鍵的值。其他可用的取值方法:
| 方法 | 說明 |
|---|---|
| get(String name) | 回傳 Object,需自行轉型。 |
| getBoolean(String name) | 取得布林值。 |
| getDouble(String name) | 取得 double 數值。 |
| getInt(String name) | 取得整數。 |
| getLong(String name) | 取得 long 數值。 |
| length() | 回傳鍵值對的數量。 |
| names() | 回傳所有鍵名稱組成的陣列。 |
實務上建議把解析包在 try-catch 裡,並改用 optJSONObject()、optString() 這類不會丟例外的版本,避免伺服器回傳格式異常時整個 App 閃退。
範例會建立一個 App,讓使用者輸入城市名稱,按下按鈕後向 OpenWeatherMap 請求 JSON,解析後顯示國家、溫度、濕度與氣壓。
| 步驟 | 做法 |
|---|---|
| 1 | 用 Android Studio 建立專案 JSONParser,Target SDK 與編譯版本都取最新。 |
| 2 | 修改 src/MainActivity.java。 |
| 3 | 修改 res/layout/activity_main.xml。 |
| 4 | 修改 res/values/string.xml。 |
| 5 | 新增 src/HandleJSON.java,負責連線與解析。 |
| 6 | 在 AndroidManifest.xml 補上 INTERNET 權限。 |
| 7 | 執行並驗證。 |
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());
}
}
package com.example.jsonparser;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
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) {
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() : "";
}
}
這裡有個值得注意的細節:網路請求被放在背景 Thread 執行,並用 parsingComplete 這個 volatile 旗標讓主執行緒等待。這是為了避開 Android 對主執行緒網路操作的限制。若換到新版 Android,更推薦改用 AsyncTask、Kotlin 協程或 Retrofit 這類工具,寫法會乾淨許多。
<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/editText1"
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/textViumXView4"
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/textViwX3"
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/textVirewX3"
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>
<?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>
裝好 App 啟動它,初始畫面只有一個位置輸入欄:
輸入城市名稱(這裡示範紐約)後按下 weather:
App 會連上 OpenWeatherMap 取得 JSON 並解析,把四個欄位填回畫面。要記得 temperature 回傳的是克耳文,換算成攝氏度需減去 273.15,這樣顯示的數字才符合一般使用者的期待。
Android MediaPlayer 教學:動手做一個音樂播放器
要在 App 裡播放音訊或影片,Android 提供了不少途徑,而最最直接的一條路就是 MediaPlayer 類別。它被封裝在 android.media 套件中,可以
Android 多語系支援:strings.xml 與 values-it 目錄
Android 的資源系統會根據裝置語言自動選擇合適的字串資源。只要將不同語言的 strings.xml 放在對應的 values 目錄,App 就能依系統設定顯示正確語
Android 實戰:手機短信驗證碼獲取與注冊全流程解析
注冊各類 App 或網站賬號時,手機短信驗證碼幾乎是標配環節。曾經只覺得「手機收驗證碼」這件事挺新奇,卻沒深究背後是怎麼實現的。如今手上的項目正好需要通過手機號注冊、並發
Android 全域變數與區域變數的使用差異
全域變數可在類別中的多個方法共用,區域變數則只在特定方法或區塊內有效。兩者在 Android 開發中的使用時機不同,混用可能造成非預期的資料狀態。 Adapter 中的