編輯:Android 開發實例
行動應用要顯示即時資訊,幾乎都得跟遠端伺服器要資料,而 JSON 就是最普遍的那種「通用語言」。它源自 JavaScript 的物件語法,但早已獨立成為一種跨平台的資料交換格式,並在許多場合取代 XML 成為主流選擇。
本章要完整走一遍 Android 上的 JSON 解析流程,示範用的資料是一段天氣回應。
Android 提供了四個 JSON 相關類別:JSONArray、JSONObject、JSONStringer、JSONTokenizer。日常開發絕大多數只需要 JSONObject 與 JSONArray。
動手寫解析程式之前,先確認你要的是哪幾個欄位。以下這段 JSON 裡,我們想抓的是溫度:
{
"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({}) | 大括號表示物件,由一組 key/value 構成。 |
| 3 | Key | 物件的鍵,固定為字串,與 value 成對出現。 |
| 4 | Value | 鍵對應的值,可能是字串、整數、double、布林或巢狀結構。 |
先把整段文字包成 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() 取得指定鍵的字串值。若欄位型別不同,改用下列方法即可:
| 編號 | 方法 | 說明 |
|---|---|---|
| 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() | 回傳所有鍵名組成的陣列。 |
這個範例會做出一个能連網的天氣查詢程式,把解析出來的國家、溫度、濕度、氣壓顯示在畫面上。
| 步驟 | 做法 |
|---|---|
| 1 | 用 Android Studio 建立專案並命名為 JSONParser,Target SDK 與 Compile With 選最新版本。 |
| 2 | 修改 src/MainActivity.java 加入主要程式碼。 |
| 3 | 修改 res/layout/activity_main.xml 加入版面元件。 |
| 4 | 修改 res/values/string.xml 加入字串資源。 |
| 5 | 新增 src/HandleJSON.java,負責抓取並解析 JSON。 |
| 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() : "";
}
}
<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/textV 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>
將 JSONParser 裝到 AVD 並啟動,正常情況下會看到這個查詢畫面:
在位置欄位輸入城市名稱(這裡示範紐約),按下 Weather:
按下按鈕後,程式會向天氣 API 提出請求、取得 JSON 並解析,把結果填進四個欄位裡。
一個實務上的小細節:這個 API 回傳的溫度單位是開爾文。若要顯示攝氏度,記得補上轉換計算。
Android MediaPlayer 教學:做一個能播放、暫停、快轉與回轉的音樂播放器
要在 App 裡播放一段音樂或影片,Android 提供了 MediaPlayer 這個進入點。它封裝了底層的編解碼與音訊/視訊追蹤流程,讓開發者以幾行程式碼就能完成播放
Android 應用在地化:字串翻譯與語言資源
在地化不只是翻譯文字,也包括讓 App 的數字、日期、貨幣與格式符合當地習慣。Android 透過資源系統,讓開發者能為不同語言準備對應內容。 建立語言資源 在 res
Android 應用在地化:字串資源與語言代碼對照
一支上架的 App,使用者可能來自任何語言環境。要讓各地使用者都讀得懂畫面上的字,就得把文字從程式碼中抽出來,按語言分別準備。Android 對這件事有完整的資源機制支援
自製 ClearEditText:為 Android 輸入框加上一鍵清除
需求與思路 本文實作一個很實用的小控件 ClearEditText:在輸入框右側放一個小圖示,點一下就能清空內容。iOS 只要設定某個屬性就能做到,但 Android 原