編輯:Android 開發實例
JSON 的全名是 JavaScript Object Notation,它把「人能讀、機器也好處理」這件事同時做到了。相較於標籤必須成對出現的 XML,JSON 沒有冗餘的閉合標籤,檔案更小、解析更快,早已成為 REST API 回應的主流格式。更省事的是,Android 本身就內建了完整的 JSON 支援,不必額外打包第三方函式庫。
本文要談的是兩個具體問題:如何把一段 JSON 文字還原成物件,以及如何逐層取出你真正需要的欄位。最後會用一個查天氣的小 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、weather、main 三個鍵;weather 的值是陣列,其餘兩個是物件。這個層級關係,直接決定了你的程式碼要呼叫 getJSONObject() 還是 getJSONArray()。
| 元素 | 說明 |
|---|---|
| Array([]) | 方括號代表陣列,元素有順序,以逗號分隔。 |
| Object({}) | 大括號代表物件,由一組又一組的鍵值交所組成。 |
| Key | 物件中的鍵一律是字串,例如 "country"、"temp"。 |
| Value | 鍵對應的值可以是字串、整數、浮點數、布林值或 null,也可以是另一層物件與陣列。 |
org.json 套件提供了 JSONArray、JSONObject、JSONStringer 與 JSONTokenizer。日常開發中最常打交道的是前兩者:JSONArray 處理有序集合,JSONObject 處理鍵值對。JSONStringer 偏向「產生」JSON 字串,JSONTokenizer 則適合需要逐段掃描的特殊情境。
第一個動作是把整段文字交給 JSONObject 的建構子,讓它完成基本的語法檢查:
String in; JSONObject reader = new JSONObject(in);
第二個動作是按層取值。碰到子物件就用 getJSONObject(),碰到單一值就用 getString()、getInt() 這類指定型別的方法:
JSONObject sys = reader.getJSONObject("sys");
country = sys.getString("country");
JSONObject main = reader.getJSONObject("main");
temperature = main.getString("temp");
JSONObject 提供的取值方法可以整理成下表:
| 方法 | 用途 |
|---|---|
| get(String name) | 回傳 Object 型別的原始值,需要自行轉型。 |
| getBoolean(String name) | 取出該鍵的布林值。 |
| getDouble(String name) | 取出該鍵的 double 數值。 |
| getInt(String name) | 取出該鍵的整數。 |
| getLong(String name) | 取出該鍵的 long 數值。 |
| length() | 回傳這個物件裡鍵值對的數量。 |
| names() | 回傳包含所有鍵名稱的字串陣列。 |
把上面的觀念做成人要用的東西:輸入城市名稱,按下按鈕後連線 OpenWeatherMap 取得 JSON,解析後顯示國家、溫度、濕度與氣壓。
驗證時建議使用實機,或先啟動好模擬器。
| 步驟 | 做法 |
|---|---|
| 1 | 用 Android Studio 建立專案,命名為 JSONParser,Target SDK 與 Compile With 都選最新的 Android SDK 版本。 |
| 2 | 修改 src/MainActivity.java,加入界面控制與觸發查詢的程式碼。 |
| 3 | 修改 res/layout/activity_main.xml,配置輸入框與結果欄位。 |
| 4 | 修改 res/values/string.xml,把畫面上用到的文字抽出來。 |
| 5 | 新增 src/HandleJSON.java,負責網路連線與 JSON 解析。 |
| 6 | 在 AndroidManifest.xml 加上 android.permission.INTERNET 權限。 |
| 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;
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() : "";
}
}
<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/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/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/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 裝到 AVD 或實機上啟動。若環境與程式碼都沒問題,會看到這樣的畫面:
接著在位置欄位輸入城市名稱,這裡以紐約為例,按下 weather 按鈕:
按下按鈕後,程式會向 OpenWeatherMap 的 API 送出請求,取回 JSON 並解析,再把欄位填回畫面。
要留意的是,這類服務回傳的溫度單位是克耳文(Kelvin)。若想顯示一般人更熟悉的攝氏度,記得做一次轉換:攝氏 = 克耳文 − 273.15。
Android 載入 Spinner 實作流程:從 XML 到 Java 的完整示範
當 App 在背後做事,畫面上一定要給使用者一點回饋,否則再快的操作也會被當成當機。Android 的進度條有兩種典型形態:一種是能看到百分比的 Loading Bar,
Android MediaPlayer 音訊播放實作
Android 提供 MediaPlayer 類別,可播放音訊與影片。最簡單的方式是使用靜態 create() 方法載入 res/raw 中的媒體檔。 MediaPlay
Android JSON 資料解析:天氣 API 實作範例
JSON 解析在 Android 中常用於 API 回傳。本文以天氣資料為例,說明如何從 JSON 字串取出溫度、濕度與氣壓。 四個常用類別 JSONArray 處理陣列
Android 開發實作:日曆專案(三)建立樣式與資源
接續日曆專案的進度,這一階段要把視覺資源整理乾淨:顏色、尺寸、Color State List、drawable 與 style 全部抽成獨立檔案。日曆的表格線以 Cel