編輯:Android 開發實例
JSON 是 JavaScript Object Notation 的縮寫,做為一種與語言無關的資料交換格式,這些年在行動端幾乎全面取代了 XML:它更輕、更好讀,解析也更快。本章要說明的是,在 Android 上如何把一段 JSON 文字還原成物件,並取出真正需要的欄位。
Android 內建四個處理 JSON 的類別:JSONArray、JSONObject、JSONStringer 與 JSONTokenizer。其中又以 JSONObject 最常派上用場。
動工之前先看清楚資料長相。以下是一段典型的天氣 JSON,我們感興趣的是 main 底下的 temp:
{ "sys": { "country":"GB", "sunrise":1381107633, "sunset":1381149604 }, "weather":[ { "id":711, "main":"Smoke", "description":"smoke", "icon":"50n" } ], "main": { "temp":304.15, "pressure":1009, } }
| 項目 | 說明 |
|---|---|
| 陣列 [ ] | 方括號代表 JSON 陣列,裡頭放的是一串同構的值。 |
| 物件 { } | 大括號代表 JSON 物件,是key-value 的集合。 |
| 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");
也就是說,getJSONObject() 用來取出嵌套的物件,getString() 則取出指定鍵的字串值。除此之外還有這些方法:
| 方法 | 說明 |
|---|---|
| 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,SDK 等級對齊較新版本。 |
| 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:
<?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 裝進 AVD 啟動,一切正常就會看到這個起始畫面:
在位置欄位輸入任一座城市,這裡示範紐約,然後按下 weather:
按下按鈕後,程式會連上 API、抓回 JSON 並完成解析,畫面上便會填入回傳的欄位值,其中包含該城市的天氣 API 溫度。
要注意的是,這個 API 回傳的溫度單位是克氏(Kelvin)。若想換成比較直覺的攝氏,記得減去 273.15 再呈現給使用者。
Android 多語言支援:用 values-it 資料夾讓 App 自動說義大利語
你的 App 可能同時裝在東京、羅馬與墨西哥城的手機上。如果介面永遠是同一種語言,等於自願放棄那些市場。Android 在資源系統的設計上早就想過這件事:只要依命名慣例準
Android Service 生命週期詳解:startService 與 bindService 的兩條路徑
Android 的應用元件各有生命週期——系統在需要時將它們實例化以回應意圖,最後再銷毀。期間它們可能處於啟用或非啟用狀態,對 Activity 而言還有可見與不可見之分
Android 頂部導航菜單左右滑動的兩種實作方案
本文示範在 Android 中實作頂部導航菜單的左右滑動效果,提供兩種方案:以 ViewPager 分頁切換,以及以 HorizontalScrollView 做連續滑動
Android 登入實作:帳號密碼驗證與三次錯誤鎖定
登入畫面負責向使用者索取帳號與密碼以驗證身分,是許多應用(如 Facebook、微博)的必備環節。本章說明如何建立登入介面,並處理安全性與錯誤嘗試次數的限制。 首先在版