編輯:Android 開發實例
JSON 這個名稱來自 JavaScript,但它早已脫離該語言,成為一門獨立的資料交換格式,也是 XML 最常被替換的對象。對 Android 開發者而言,理解 JSON 解析的關鍵不在背誦 API,而在看懂「資料的層級」——知道要的值藏在第幾層、是物件還是陣列,剩下的只是照著往下取。
JSONArray 處理方括號的序列;JSONObject 處理花括號的鍵值集合;JSONStringer 用來反向組出 JSON 字串;JSONTokenizer 則是最底層的切詞工具,一般開發 mostly 不會直接碰到。本文的示範全部圍繞 JSONObject。
以下是一段天氣服務的回應。假設我們關心的是溫度,那麼目標路徑就是 main → temp:
{
"sys": { "country": "GB", "sunrise": 1381107633, "sunset": 1381149604 },
"weather": [
{ "id": 711, "main": "Smoke", "description": "smoke", "icon": "50n" }
],
"main": { "temp": 304.15, "pressure": 1009 }
}
weather 就是陣列,取用時要給索引,例如 getJSONArray("weather").getJSONObject(0)。sys 與 main 都是物件。階段一:建構物件。把整段字串交給建構子,一次完成解析:
String in; // 取得的原始回應文字 JSONObject reader = new JSONObject(in);
階段二:分層取值。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():回傳包含所有鍵名稱的陣列。另外,has(String name) 可以在取值前先確認鍵是否存在,避免不必要的例外。
這個範例建立一個基礎的天氣應用,讓使用者輸入城市,程式連上服務取得 JSON 並解析後顯示結果。
src/MainActivity.java 加入必要程式碼。res/layout/activity_main.xml 加入對應的 XML 元件。res/values/strings.xml 加入字串。src/ 新增 HandleJSON.java,負責取得並解析資料。AndroidManifest.xml 加入上網權限。主活動 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 = "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);
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/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/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/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>
字串 res/values/strings.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 啟動,一切正常時會出現這個視窗:
在位置欄位輸入任一座城市(本例使用紐約),畫面如下:
按下 Weather 鈕,程式會連上服務、下載 JSON、逐層解析並填入欄位。
這個服務回傳的溫度是開爾文。若要顯示成比較直覺的攝氏度,套用 K − 273.15 的換算即可。同理,氣壓單位為 hPa、濕度為百分比,顯示前值得對照一次官方文件確認。
最後提醒一個實務陷阱:這個範例用 while(obj.parsingComplete); 忙等來同步背景執行緒,會讓 CPU 空轉並且在慢網路下拖住 UI。正式專案請改用回呼、LiveData、Coroutine 或 Retrofit 的 enqueue 機制,並記得在解析失敗時給使用者看得懂的錯誤訊息,而不是讓它靜靜地停在「temperature」這個預設字串上。
Android 進度條教學:用 Loading Spinner 表達「還不知道要等多久」
當 App 要執行一段耗時的工作,例如從網路下載資料,使用者需要一個「它還在動」的訊號。Android 用 ProgressBar 這個元件來表達等待狀態,而它主要有兩種
Java 基本資料類型在 Android 開發中的重點整理
資料類型的整體分類 Java 的資料類型可分為基本資料類型與參考資料類型。Android 開發中經常使用基本資料類型來處理數字、字元與邏輯判斷,因此理解其特性非常重要。
Android JSON 資料解析:JSONObject 與天氣資訊抓取
在 Android 開發中,JSON 解析幾乎是網路應用的必備技能。無論是氣象、新聞、社群或商品資料,後端常會以 JSON 格式回傳結果。本文說明如何從 JSON 中取出
ListView 分頁加載實作:滚动到底自動載入更多資料
ListView 是 Android 最常用的控件之一。實務上如果一次把幾千筆資料塞進去,畫面會卡、記憶體會爆,因此分頁加載幾乎是必備技巧。 本範例把「載入更多」的觸發點