編輯:Android 開發實例
行動裝置上的資料,大多以 JSON 的形式從伺服器流過來。它源自 JavaScript 的物件寫法,卻早已成為語言中立的通用格式,憑著結構清爽、可讀性高,逐步取代 XML 成為 API 回應的主流選擇。
Android 內建四個處理 JSON 的類別:JSONArray、JSONObject、JSONStringer 和 JSONTokenizer。日常開發中,最常打交道的是 JSONObject。
解析工作可以拆成兩步:先確認你要抓哪個欄位,再依結構逐層剝開。以下面這段天氣資料為例,目標是溫度:
{ "sys": { "country":"GB", "sunrise":1381107633, "sunset":1381149604 }, "weather":[ { "id":711, "main":"Smoke", "description":"smoke", "icon":"50n" } ], "main": { "temp":304.15, "pressure":1009, } }
| 編號 | 元素 | 說明 |
|---|---|---|
| 1 | Array [ ] | 方括號表示陣列,用於收錄一組資料。 |
| 2 | Object { } | 大括號表示物件,是構成 JSON 的基礎單位。 |
| 3 | Key | 物件中的鍵必為字串;鍵與值成對出現,共同組成一個物件。 |
| 4 | Value | 鍵所對應的值,可能是字串、整數、浮點數或布林值。 |
先把整段 JSON 文字塞進 JSONObject 建構子:
String in; JSONObject reader = new JSONObject(in);
再依巢狀結構逐層取值。內層物件要先用 getJSONObject() 取出,才能讀取其中的欄位:
JSONObject sys = reader.getJSONObject("sys");
country = sys.getString("country");
JSONObject main = reader.getJSONObject("main");
temperature = main.getString("temp");
除了 getJSONObject() 與 getString(),JSONObject 還有一整組型別化的取值方法:
| 編號 | 方法 | 說明 |
|---|---|---|
| 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() | 回傳一個陣列,列出此物件所有的鍵名稱。 |
接下來把上面的知識用在真實場景:使用者輸入城市名稱,App 連網取得 JSON,解析後顯示國家、溫度、濕度與氣壓。
| 步驟 | 做法 |
|---|---|
| 1 | 以 Android Studio 建立專案 JSONParser,Target SDK 與編譯版本都採用最新的 Android SDK。 |
| 2 | 修改 src/MainActivity.java,加入主要程式碼。 |
| 3 | 修改 res/layout/activity_main.xml,加入對應的 XML 元件。 |
| 4 | 修改 res/values/string.xml,補齊字串資源。 |
| 5 | 新增 src/HandleJSON.java,負責抓取並解析遠端資料。 |
| 6 | 修改 AndroidManifest.xml,加上網路權限。 |
| 7 | 執行 App,選擇裝置並驗證結果。 |
主活動檔 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 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() : "";
}
}
版面檔 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/text iew1" android:layout_alignParentRight="true" android:ems="10" /> <TextView android:id="@+id/text iew2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/text iew1" android:layout_below="@+id/text iew1" android:layout_marginTop="68dp" android:text="@string/country" android:textAppearance="?android:attr/textAppearanceSmall" /> <EditText android:id="@+id/editText2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/text iew2" android:layout_below="@+id/text iew2" android:ems="10" > <requestFocus /> </EditText> <TextView android:id="@+id/text iew3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/text iew2" android:layout_below="@+id/editText2" android:layout_marginTop="19dp" android:text="@string/temperature" android:textAppearance="?android:attr/textAppearanceSmall" /> <EditText android:id="@+id/editText3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/editText2" android:layout_below="@+id/text iew3" android:ems="10" /> <TextView android:id="@+id/text iew4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/text iew3" android:layout_below="@+id/editText3" android:layout_marginTop="32dp" android:text="@string/humidity" android:textAppearance="?android:attr/textAppearanceSmall" /> <EditText android:id="@+id/editText4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/editText1" android:layout_below="@+id/text iew4" android:ems="10" /> <TextView android:id="@+id/text iew5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/text iew4" android:layout_below="@+id/editText4" android:layout_marginTop="21dp" android:text="@string/pressure" android:textAppearance="?android:attr/textAppearanceSmall" /> <EditText android:id="@+id/editText5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/editText4" android:layout_below="@+id/text iew5" 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="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 一定要宣告 android.permission.INTERNET,否則網路請求會直接失敗:
<?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 並啟動,設定無誤就會看到初始畫面:
在位置欄位輸入想查的城市,這裡示範紐約:
按下 Weather 之後,App 會向天氣服務索取 JSON 並完成解析,把結果填進各個欄位。
要留意的是,回傳的溫度是凱氏。若想轉成比較直覺的攝氏,記得減去 273.15。
Android 自定義軟鍵盤:打造中文與數字輸入鍵盤
軟鍵盤的核心類別 Android 自定義軟鍵盤主要使用 Keyboard 與 KeyboardView。Keyboard 描述按鍵排列,KeyboardView 負責繪製
Android 登入表單的錯誤回饋怎麼設計?Toast、剩餘次數與按鈕狀態
登入流程的成敗,往往不在「帳密對不對」,而在「錯了的時候使用者知不知道錯在哪」。一個好的登入畫面會即時告訴你三件事:帳密錯誤、還剩幾次機會、以及機會用完了。本章就用一個小
從支付寶與微信首頁看 Android 事件分發:可拖曳 GridView 實戰
很多 Android 開發者會以支付寶、微信首頁作為事件分發的練習題,因為這類頁面常同時包含 ViewPager、ScrollView、GridView 與拖曳排序,很容
Android 本地化入門:用 values-語系 資料夾做好多國語言支援
一支 App 上線後,使用者可能來自任何國家。若畫面上永遠只有一種語言,對不熟悉該語言的人來說形同不可用。本地化要解決的就是這個問題:讓 App 依裝置的語言環境,自動呈