編輯:Android 開發實例
做過網路相關的 App 就會知道,伺服器回傳的資料幾乎都是 JSON。它是 JavaScript Object Notation 的縮寫,憑藉著結構清晰、沒有冗餘標籤這兩個優點,早已取代 XML 成為資料交換的標準格式。Android 內建了處理它的工具,不需要引入額外套件。
本文用一個天氣查詢 App 當例子,把 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,或另一層結構。 |
org.json 套件裡有四個成員:JSONArray、JSONObject、JSONStringer 與 JSONTokenizer。解析 API 回應時,只需要 JSONArray 與 JSONObject;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() | 回傳鍵名稱陣列。 |
這個 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() : "";
}
}
值得留意的是 fetchJSON() 把工作丟到背景 Thread,再用 parsingComplete 這個 volatile 旗標讓主執行緒等待。之所以要這樣寫,是因為新版 Android 禁止在主執行緒進行網路連線,直接寫會收到 NetworkOnMainThreadException。
<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/textV8iew3"
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/textV8iew3"
android:layout_marginTop="32dp"
android:text="@string/humidity"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView android:id="@+id/textVi8ew5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView4"
android:layout_below="@+id/textV8iew4"
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/textV8iew3"
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/textVi8ew3"
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/textV8iew5"
android:layout_alignBottom="@+id/textV8iew5"
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、解析後把結果填回畫面。最後提醒一個實務細節:這類 API 回傳的溫度是克耳文,若要顯示攝氏度必須換算(攝氏 = 克耳文 − 273.15);濕度則是百分比,氣壓單位為 hPa。把單位處理好,畫面上的數字對使用者才有意義。
Android 模擬定位實作教學:權限宣告、狀態偵測與座標注入
想在 App 裡驗證定位功能,卻不方便真的出門跑一條路線?Android 系統本身內建了「模擬位置」機制:只要在開發者選項中指定一支代理程式,系統 GPS 就會回報你自己
Android AIDL 跨進程服務完整實作:從服務端到客戶端全流程
在 Android 裡有所謂的 Service,但要實現「跨應用程式共享資料」時,單純的 Service 是不夠的,這時候就需要 Android Interface De
Android MediaPlayer:打造可播放、暫停與快轉的音樂播放器
MediaPlayer 的角色 Android 提供 MediaPlayer 類別,用來控制音訊與影片播放。最簡單的用法是透過靜態 create 方法載入 res/raw
Android 加載 Spinner 實作指南:ProgressBar 樣式、生命週期與解除時機
在 Android 中,任務的執行進展可以透過載入進度條來呈現。進度條有兩種形態:加載欄與加載微調(spinner)。前者用於能算出百分比的场合,後者則是給那些「還要多久