編輯:Android 開發實例
JSON 的全稱是 JavaScript Object Notation,中文常譯作「JavaScript 物件符號法」。雖說名字裡有 JavaScript,格式本身卻是語言中立的,任何平台都能使用。因為語法輕巧、資料量小、解析成本低,它在資料交換這件事上已經是 XML 之外最普遍的选择。
本章要處理的是解析這一側:如何把一段 JSON 文字讀進 Android,並取出需要的欄位。
Android 提供了四個 JSON 相關類別:JSONArray、JSONObject、JSONStringer、JSONTokenizer。解析時以前兩者為主。
一開始先確認目標欄位的位置。以這段天氣資料為例,我們要的是溫度:
{ "sys": { "country":"GB", "sunrise":1381107633, "sunset":1381149604 }, "weather":[ { "id":711, "main":"Smoke", "description":"smoke", "icon":"50n" } ], "main": { "temp":304.15, "pressure":1009, } }
| 項目 | 說明 |
|---|---|
Array [ | 中括號代表陣列,用來收錄多筆資料。 |
Object { | 大括號代表物件,由鍵值對組成。 |
| Key | 物件中的鍵,型別固定為字串。鍵與值配對後構成一個物件。 |
| Value | 鍵所對應的值,可能是字串、整數、double 等型別。 |
先把整段文字包裝成 JSONObject:
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");
若清楚知道欄位型別,可以直接用對應方法,省下手動轉換:
| 方法 | 說明 |
|---|---|
get(String name) | 只回傳值,型別維持 Object。 |
getBoolean(String name) | 回傳指定鍵的布林值。 |
getDouble(String name) | 回傳指定鍵的 double 值。 |
getInt(String name) | 回傳指定鍵的整數值。 |
getLong(String name) | 回傳指定鍵的 long 值。 |
length() | 回傳此物件中名稱/值對的數量。 |
names() | 回傳一個陣列,內含此物件所有的鍵名稱。 |
這個範例示範 JSONObject 的實際操作,做出一個能向天氣 API 索取資料、解析後顯示結果的應用。
你可以在實機或模擬器上執行驗證。
| 步驟 | 要做的事 |
|---|---|
| 1 | 用 Android Studio 建立專案,命名為 JSONParser。Target SDK 與 Compile With 設為最新版本以使用較新的 API。 |
| 2 | 修改 src/MainActivity.java,加入程式碼。 |
| 3 | 修改 res/layout/activity_main.xml,加入元件。 |
| 4 | 修改 res/values/string.xml,加入字串資源。 |
| 5 | 新增 src/HandleJSON.java,負責抓取與解析。 |
| 6 | 修改 AndroidManifest.xml,加上網路權限。 |
| 7 | 執行 App 並驗證。 |
主活動檔 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) { // Inflate the menu; this adds items //to the action bar if it is present. 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.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.json.JSONObject; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserFactory; 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) { // TODO Auto-generated catch block 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 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); // Starts the query 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/findViewById" 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/findViewById" android:layout_below="@+id/findViewById" 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/findViewById" 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/findViewById" 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/findViewById" android:layout_alignBottom="@+id/findViewById" 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 鈕:
按下按鈕後,App 會連線到天氣服務取得 JSON 並完成解析。若輸入紐約,回傳結構與先前的樣本一致。
提醒一個實務細節:這個 API 的溫度單位是開爾文。若想顯示為比較親近的攝氏度,需要自行轉換。
Android 載入 Spinner:非確定性進度條應用
當 App 需要執行一段時間,但無法得知確切進度時,可以使用非確定性進度條,也就是俗稱的 Spinner。它能讓使用者知道系統仍在處理中。 Spinner 的定位 And
Android 設計模式之策略模式:以動畫 Interpolator 為例
策略模式其實特別簡單(看到這句話,是不是心裡一下放鬆了?)。 舉個例子:排序。官方定義一個排序接口 ISort,裡面有一個 sort() 方法;民間各自實現——冒泡、快速
手把手做 Android 登入頁:表單、驗證與錯誤嘗試的處理
登入畫面是許多 App 的第一道門。使用者要嘛成功進入,要嘛被擋在門外——而這中間的體驗細節,往往決定了對這個 App 的第一印象。本文從版面配置寫到程式邏輯,做出一個具
Android 自定義權限的實作方式
自定義權限是 Android 組件保護的重要機制。透過自定義權限,開發者可限制特定 Activity、Service 或其他組件只能被持有指定權限的應用呼叫。定義權限的應