編輯:Android 開發實例
JSON(JavaScript Object Notation)是一種輕量、獨立於語言的資料交換格式,語法比 XML 精簡得多,因此在行動端 API 的往來中幾乎已成標準。本章說明如何在 Android 上解析 JSON 並取出需要的欄位。
Android 內建四個處理 JSON 的類別:JSONArray、JSONObject、JSONStringer 與 JSONTokenizer。其中又以 JSONObject 最常使用。
第一步永遠是釐清你感興趣的欄位。以下面這份天氣資料為例,我們關心的是溫度:
{
"sys": {
"country":"GB",
"sunrise":1381107633,
"sunset":1381149604
},
"weather":[
{
"id":711,
"main":"Smoke",
"description":"smoke",
"icon":"50n"
}
],
"main": {
"temp":304.15,
"pressure":1009,
}
}
| 元件 | 說明 |
|---|---|
| Array([]) | 方括號代表 JSON 陣列 |
| Object({}) | 大括號代表 JSON 物件 |
| Key | 物件中的鍵,為字串形式;鍵/值配對組成一個物件 |
| Value | 每個鍵對應的值,可能是字串、整數、double 等型別 |
解析的第一步是建立 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() 則回傳指定鍵的字串值。
JSONObject 還提供下列方法,讓解析更靈活:
| 方法 | 說明 |
|---|---|
| get(String name) | 回傳值,但維持原始的物件型別 |
| getBoolean(String name) | 回傳指定鍵的布林值 |
| getDouble(String name) | 回傳指定鍵的 double 值 |
| getInt(String name) | 回傳指定鍵的整數值 |
| getLong(String name) | 回傳指定鍵的 long 值 |
| length() | 回傳這個物件中鍵值對的數量 |
| names() | 回傳包含所有鍵名稱的字串陣列 |
這個範例建立一個簡易的天氣應用,讓使用者輸入城市名稱,再從天氣 API 取得 JSON 並解析顯示。
| 步驟 | 說明 |
|---|---|
| 1 | 用 Android Studio 建立專案並命名為 JSONParser,Target SDK 選擇較新版本 |
| 2 | 修改 src/MainActivity.java,加入必要程式碼 |
| 3 | 修改 res/layout/activity_main.xml,加入對應元件 |
| 4 | 修改 res/values/string.xml,補上字串資源 |
| 5 | 在 src/HandleJSON.java 新增類別,負責抓取並解析 JSON |
| 6 | 修改 AndroidManifest.xml,加入網路權限 |
| 7 | 執行 App,選擇真機或模擬器安裝並驗證結果 |
主 Activity 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 = "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" />
<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,注意必須加上 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>
執行應用程式並在 AVD 上啟動,會看到如下畫面:
在位置欄位輸入城市名稱(範例中輸入紐約),按下 weather 按鈕:
按下按鈕後,應用程式會連線天氣 API、抓取 JSON 並解析其中的欄位,再把結果填回畫面。
兩點實務提醒:其一,回傳的溫度是開爾文(Kelvin),若要顯示攝氏度必須再減去 273.15;其二,Android 3.0 以後不允許在主執行緒進行網路連線,範例因此把請求放在背景執行緒中,並以 parsingComplete 旗標等待結果,正式專案建議改用非同步任務或 coroutine 來取代這種忙等寫法。
Android 視圖控件架構解析:View 與 ViewGroup
控件樹的組成 Android 的視圖控件大致分為兩類:ViewGroup 與 View。ViewGroup 充當父容器,負責包含並管理子 View,兩者交錯組合便形成一棵
深入淺析 Android Fragment(上篇):從誕生到動態操作
曾有一段時間,好像聊什麼都能扯到 Fragment,做什麼都要問一句「Fragment 能不能實現」——現在回想起來確實有點誇張,但它會紅,背後是有明確理由的。 Fra
Android時間與日期元件用法實例:TimePicker 與 DatePicker
繼上一篇關於時間與日期設定的示例之後,本文接著介紹 Android 介面元件中與時間、日期相關的設定元件,希望能對大家有所幫助。具體如下: 時間日期設定元件:TimePi
Android MediaPlayer 完整指南:從 create() 到快轉快退與資源釋放
要在 App 裡播放音樂,Android 給的第一個答案就是 MediaPlayer。它位於系統媒體播放服務之上,把容器格式解析、音訊解碼、輸出路由這些麻煩事都封裝起來,