編輯:Android 開發實例
JSON 的全名是 JavaScript Object Notation,但今日它早已脫離 JavaScript 的框架,成為跨語言通用的資料交換格式,也是 XML 在 API 世界裡最主要的替代方案。它沒有冗餘的封閉標籤,人眼可讀、機器好解析,行動裝置在行動網路上傳輸時尤其吃香。
本章示範如何在 Android 上把一段 JSON 文字拆解成可用的資料。Android 內建了四個相關類別:JSONArray、JSONObject、JSONStringer 與 JSONTokenizer;其中解析回應以 JSONObject 搭配 JSONArray 最為常見。
第一步永遠是釐清需求。以下這段天氣資料中,我們只關心溫度:
{ "sys": { "country":"GB", "sunrise":1381107633, "sunset":1381149604 }, "weather":[ { "id":711, "main":"Smoke", "description":"smoke", "icon":"50n" } ], "main": { "temp":304.15, "pressure":1009, } }
| 編號 | 元素與說明 |
|---|---|
| 1 | Array([]) 方括號代表陣列,元素依序排列。 |
| 2 | Object({}) 大括號代表物件,由鍵值對組成。 |
| 3 | Key 鍵必為字串,鍵與值配對後構成一個物件。 |
| 4 | Value 值可以是字串、整數、double、布林,或另一層物件/陣列。 |
先把整段字串交給 JSONObject 建構子:
String in; JSONObject reader = new JSONObject(in);
接著逐層取出所需的值:
JSONObject sys = reader.getJSONObject("sys"); country = sys.getString("country"); JSONObject main = reader.getJSONObject("main"); temperature = main.getString("temp");
可用的取值方法還包括:
| 編號 | 方法與說明 |
|---|---|
| 1 | get(String name) 以 Object 型別回傳值。 |
| 2 | getBoolean(String name) 回傳布林值。 |
| 3 | getDouble(String name) 回傳 double。 |
| 4 | getInt(String name) 回傳整數。 |
| 5 | getLong(String name) 回傳 long。 |
| 6 | length() 回傳鍵值對數量。 |
| 7 | names() 回傳包含所有鍵名的陣列。 |
若欄位屬於選填性質,改用 optString()/optInt() 這類方法可避免丟出 JSONException;陣列則用 getJSONArray() 取出後,再以 length() 搭配迴圈逐一處理。
以下範例做出一個天氣查詢 App,輸入城市後連線 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 負責抓取與解析。 |
| 6 | 於 AndroidManifest.xml 加上 INTERNET 權限。 |
| 7 | 執行、安裝並驗證。 |
主活動:
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()); } }
網路與解析:
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() : ""; } }
版面:
<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/textViem1" 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/textViem1" android:layout_alignParentRight="true" android:ems="10" /> <TextView android:id="@+id/textViem2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textViem1" android:layout_below="@+id/textViem1" android:layout_marginTop="68dp" android:text="@string/country" android:textAppearance="?android:attr/textAppearanceSmall" /> <TextView android:id="@+id/textViem3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textViem2" android:layout_marginTop="19dp" android:text="@string/temperature" android:textAppearance="?android:attr/textAppearanceSmall" /> <TextView android:id="@+id/textViem4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textViem3" android:layout_below="@+id/textViem3" android:layout_marginTop="32dp" android:text="@string/humidity" android:textAppearance="?android:attr/textAppearanceSmall" /> <TextView android:id="@+id/textViem5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textViem4" android:layout_below="@+id/textViem4" 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/textViem3" android:layout_toRightOf="@+id/textViem3" android:ems="10" > <requestFocus /> </EditText> <EditText android:id="@+id/editText3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/textViem3" android:layout_alignBottom="@+id/textViem3" 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/textViem5" 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/textViem5" android:layout_alignBottom="@+id/textViem5" 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>
字串與權限:
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">JSONParser</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>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.yiibai.jsonparser"> <uses-permission android:name="android.permission.INTERNET"/> <application android:label="@string/app_name"> <activity android:name=".MainActivity"> <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 並解析,把結果填入畫面各欄位。
最後兩點提醒:回傳的溫度是開爾文,換成攝氏度需減去 273.15;另外,Android 3.0 以後不允許在主執行緒進行網路連線,範例中的空迴圈等待也會阻塞 UI,正式開發請改用 ExecutorService、Kotlin 協程或 WorkManager 搭配回呼來更新畫面。
Android Studio 整合 OpenCV 開發環境的完整建置流程
前言 想在 Android 專案裡使用 OpenCV 進行影像處理或人臉偵測,第一步永遠是「把開發環境搭起來」。本文以 Android Studio 為主,示範如何從官方
Android 應用國際化入門:依地區切換字串資源
國際化應用的第一步,是把畫面文字從程式碼中抽出,改放進資源檔。這樣一來,新增語言時不必修改程式邏輯。 資源資料夾命名 Android 使用 values 加上語言代碼的方
Android JSON 解析完整指南
JSON 是 JavaScript Object Notation 的縮寫,它是一種與語言無關的資料交換格式,被廣泛視為 XML 的理想替代方案。本章將說明如何在 And
Android 撥號盤 T9 搜尋實作分享
通訊錄或撥號盤應用常需要 T9 搜尋與號碼搜尋。實作時需處理聯絡人載入、拼音轉換與搜尋效能。 T9 資料準備 若每次開啟撥號盤都重新讀取聯絡人並轉換拼音,可能造成延遲