編輯:Android 開發實例
JSON 是 JavaScript Object Notation 的縮寫,它是一種與語言無關的資料交換格式,也是 XML 廣受歡迎的替代方案。本章將說明如何在 Android 中解析 JSON 資料,並從中取出我們感興趣的欄位。
Android 內建了四個處理 JSON 的類別:JSONObject、JSONArray、JSONStringer 與 JSONTokenizer。
解析的第一步,是先確認你想取用的欄位。以下面這段 JSON 為例,我們感興趣的是溫度:
{
"sys": {
"country":"GB",
"sunrise":1381107633,
"sunset":1381149604
},
"weather":[
{
"id":711,
"main":"Smoke",
"description":"smoke",
"icon":"50n"
}
],
"main": {
"temp":304.15,
"pressure":1009
}
}
一份 JSON 檔由多個元件組成,各元件的意義如下:
| 元件 | 說明 |
|---|---|
| Array([]) | 方括號代表 JSON 陣列。 |
| Objects({}) | 大括號代表 JSON 物件。 |
| Key | 物件中的鍵,是字串;鍵與值成對組成一個物件。 |
| Value | 每個鍵對應的值,可能是字串、整數或 double 等型別。 |
要解析 JSON,首先建立一個 JSONObject,並把包含 JSON 資料的字串傳入建構子:
String in; JSONObject reader = new JSONObject(in);
最後一步是逐層解析。由於 JSON 由不同的物件與鍵值對組成,JSONObject 針對不同層級提供了各自的取用方法:
JSONObject sys = reader.getJSONObject("sys");
country = sys.getString("country");
JSONObject main = reader.getJSONObject("main");
temperature = main.getString("temp");
其中 getJSONObject() 會回傳指定鍵的 JSON 物件,getString() 則回傳指定鍵的字串值。除此之外,還有其他常用的取值方法:
| 方法 | 說明 |
|---|---|
| get(String name) | 以物件型別回傳指定鍵的值。 |
| getBoolean(String name) | 回傳指定鍵的布林值。 |
| getDouble(String name) | 回傳指定鍵的 double 值。 |
| getInt(String name) | 回傳指定鍵的整數值。 |
| getLong(String name) | 回傳指定鍵的 long 值。 |
| length() | 回傳此物件中鍵值對的數量。 |
| names() | 回傳包含所有鍵名稱的陣列。 |
以下範例展示如何使用 JSONObject,打造一個能向天氣 API 請求 JSON 資料並解析顯示的天氣應用。
操作步驟:
src/MainActivity.java,加入必要程式碼。res/layout/activity_main.xml,加入對應的 XML 元件。res/values/string.xml,加入必要字串。src/ 新增 HandleJSON.java,負責抓取並解析 JSON。AndroidManifest.xml,加入網路權限。主活動文件 src/com.example.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.example.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/textView1" android:layout_alignParentRight="true"
android:ems="10" />
<TextView android:id="@+id/textV 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>
字串資源 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 中加入網路權限:
<uses-permission android:name="android.permission.INTERNET"/>
運行應用後,初始畫面如下:
在位置欄位輸入任意城市(例如 New York),按下「Weather」按鈕:
按下按鈕後,應用會連線到天氣 API、取得 JSON 並解析顯示結果。
請特別注意:此 API 回傳的溫度單位是克氏(Kelvin),若想轉換為更易讀的攝氏度,必須再進一步換算。
Android MediaPlayer 多媒體播放教學:從 create() 到 release()
Android 提供了多種方式來控制音訊與影片檔案及串流的播放,其中最常用的一條路徑就是透過 MediaPlayer 這個類別。 MediaPlayer 是內建媒體播放
Android 應用程式本地化:讓 App 說不同國家的語言
同一個 App 可能會被義大利、日本、巴西的使用者打開。若希望它在各地都顯得自然,就必須處理語言、數字、日期等在地化的細節。Android 在這件事上提供了相當完整的資源
Android 模擬器安裝 APK 圖文步驟
若已安裝 Android SDK,並啟動模擬器,就可以透過 adb 將 APK 安裝到模擬器中。以下為簡易流程。準備 APK 與 platform-tools將要安裝的
Android 登入畫面實作:帳號驗證與錯誤次數鎖定
登入畫面是許多應用的必備環節,它負責向使用者索取帳號與密碼,以驗證身分並進入特定功能,例如登入 Facebook、微博等服務。本章將說明如何打造一個登入介面,並進一步處理