編輯:Android 開發實例
JSON 的全名是 JavaScript Object Notation。它其實和 JavaScript 沒有綁定關係,而是一套獨立、輕量、人類也讀得懂的資料交換格式。在行動端開發裡,JSON 幾乎完全取代了 XML 的角色:結構清楚、体积小、解析成本低,大多數後端服務預設都回傳 JSON。本章要說明的,就是在 Android 上如何把一段 JSON 文字變成 App 真正能使用的資料。
Android SDK 內建了四個與 JSON 相關的類別:JSONArray、JSONObject、JSONStringer 與 JSONTokenizer。前兩個最常使用,分別負責陣列與物件的讀寫;JSONStringer 偏向「組出」JSON 字串,JSONTokenizer 則提供逐段掃描的能力。
動手之前,先把想抓的欄位看清楚。以下是一段典型的天氣服務回應,我們真正感興趣的是其中的溫度:
{
"sys": {
"country":"GB",
"sunrise":1381107633,
"sunset":1381149604
},
"weather":[
{
"id":711,
"main":"Smoke",
"description":"smoke",
"icon":"50n"
}
],
"main": {
"temp":304.15,
"pressure":1009,
}
}
第一步,把含有 JSON 內容的字串交給 JSONObject 建構子:
String in; JSONObject reader = new JSONObject(in);
第二步,依結構逐層取出資料。上例裡 sys 與 main 都是巢狀物件,而 weather 是陣列,因此取值方式各不相同:
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():回傳一個陣列,內容是此物件所有的鍵名稱。下面的範例建立一個最簡樸的天氣查詢程式:使用者輸入城市名稱,程式呼叫開放式天氣 API、下載 JSON、解析後把國家、溫度、濕度與氣壓顯示在畫面上。要實際跑起來,請務必用真機或模擬器,因為需要網路。
操作步驟:
src/MainActivity.java,加入查詢與顯示邏輯。res/layout/activity_main.xml,補上輸入框、按鈕與結果欄位。res/values/string.xml,把畫面文字抽成字串資源。src/HandleJSON.java,負責下載與解析 JSON。AndroidManifest.xml 加上網路權限。主活動的內容:
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());
}
}
負責連線與解析的 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.SupSuppressLint;
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/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" />
<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="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 加上 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 裝到模擬器啟動,如果環境都設定正確,會看到如下的初始畫面:
接著在位置欄位輸入任意城市,這裡以紐約為例,按下 Weather 按鈕:
按下按鈕後,程式會連上開放式天氣 API、抓取對應城市的 JSON 並解析,再把欄位填回畫面。
要特別留意的是,這個 API 回傳的溫度單位是開爾文。如果想顯示成人們熟悉的攝氏度,必須自己做一次轉換(攝氏 = 開爾文 − 273.15)。
Android 本地化入門:靠資源資料夾自動切換語言
你的 App 可能同時被台灣、日本、德國的使用者開啟。如果介面永遠只有一種語言,對不諳該語言的人來說就是一道門檻。本地化要處理的範圍包括文字、數字格式、日期寫法,乃至於圖
Android 開機自啟實作:攔截 BOOT_COMPLETED 廣播
我們有時會希望 App 能在 Android 裝置開機完成後自動啟動,就像 Windows 裡那些常駐程式一樣——例如某些背景 Service 需要定期從網路上更新內容。
動手做一個 Android 音樂播放器:MediaPlayer、ListView 與 SeekBar 的整合
做一個音樂播放器,是熟悉 Android 元件最快的方式:它同時用到 ListView 顯示清單、MediaPlayer 控制播放、SeekBar 呈現並調整進度,還牽涉
Android 登入畫面完整教學:從 inputType 密碼欄到錯誤次數計數器
登入應用程式的畫面,用來詢問憑證以登入某個特定的應用,例如 Facebook、微博等服務。本章要介紹的是:如何建立一個登入介面,以及如何處理安全性與錯誤嘗試這兩件事。