編輯:Android 開發實例
JSON 的全名是 JavaScript Object Notation(JavaScript 物件符號法),它是一種與程式語言無關的輕量級資料交換格式。語法乾淨、可讀性高,因此在行動端開發裡,它幾乎已經取代 XML 成為伺服器與 App 溝通的首選。本章要談的是:如何在 Android 上把一段 JSON 字串讀進來,並且精準地取出真正需要的資訊。
Android 平台內建了四個處理 JSON 的類別:JSONObject、JSONArray、JSONStringer 與 JSONTokenizer。日常解析最常搭配使用的是前兩者。
第一步永遠是釐清需求:你想從這份資料裡拿到什麼?以下面這段天氣 API 的回應為例,我們感興趣的是溫度。
{ "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 | 物件中的鍵一律是字串,例如 country、temp。鍵與值配成一組,構成一個 JSON 物件。 |
| Value | 每個鍵對應的值可能是字串、整數、浮點數、布林或另一層物件/陣列。 |
解析的起點是把整段文字交給 JSONObject 建構子,建立一個物件實例:
String in; JSONObject reader = new JSONObject(in);
接著逐層往下走。JSON 通常是一層包一層的結構,因此 JSONObject 針對不同層級提供了不同的取值方法。取得子物件用 getJSONObject(),取得字串值用 getString():
JSONObject sys = reader.getJSONObject("sys"); country = sys.getString("country"); JSONObject main = reader.getJSONObject("main"); temperature = main.getString("temp");
除了這兩個,JSONObject 還有一整組型別明確的取用方法,能少掉不少手動轉型的麻煩:
| 方法 | 用途 |
|---|---|
get(String name) | 回傳該鍵的值,型別維持為 Object。 |
getBoolean(String name) | 回傳布林值。 |
getDouble(String name) | 回傳 double 數值。 |
getInt(String name) | 回傳整數。 |
getLong(String name) | 回傳 long 數值。 |
length() | 回傳這個物件裡鍵值對的數量。 |
names() | 回傳一個陣列,內容是此物件所有的鍵名稱。 |
下面這個範例示範 JSONObject 的實際用法。程式會向天氣 API 送出請求,把回傳的 JSON 解析後,將國家、溫度、濕度與氣壓顯示在畫面上。
你可以把 App 跑在實機或模擬器上驗證。
| 步驟 | 要做的事 |
|---|---|
| 1 | 用 Android Studio 建立專案,命名為 JSONParser。建立時請把 Target SDK 與 Compile With 設為最新版本的 Android SDK,才能使用較新的 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/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」按鈕:
按下按鈕後,App 會連上線上查詢天氣,取得 JSON 並完成解析。若輸入紐約,服務端回傳的內容大致如下:
值得注意的是,這個 API 回傳的溫度單位是開爾文。如果你想顯示成比較直覺的攝氏度,需要自己做一次轉換(攝氏 = 開爾文 − 273.15)。
Android AppWidgetProvider 的使用介紹
AppWidgetProvider 主要用於在桌面顯示插件。開發時通常需要準備一個 appwidget-provider 配置檔,用來宣告初始布局、最小寬高與更新週期,再
Android 登入表單的錯誤回饋怎麼設計?Toast、剩餘次數與按鈕狀態
登入流程的成敗,往往不在「帳密對不對」,而在「錯了的時候使用者知不知道錯在哪」。一個好的登入畫面會即時告訴你三件事:帳密錯誤、還剩幾次機會、以及機會用完了。本章就用一個小
Android 解析 JSON:從 Array、Object 到 Key/Value
JSON 的全稱是 JavaScript Object Notation,中文常譯作「JavaScript 物件符號法」。雖說名字裡有 JavaScript,格式本身卻是
Android JSON 解析完整教學
JSON 是 JavaScript Object Notation 的縮寫,它是一種與語言無關的資料交換格式,憑藉著輕量、易讀的特性,成為 XML 之外相當受歡迎的替代方