編輯:Android 開發實例
JSON(JavaScript Object Notation)是一種與程式語言無關的輕量資料交換格式,語法簡單、可讀性高,早已成為 XML 之外的主流選擇。本章示範如何在 Android 上解析 JSON 檔,並取出真正需要的資訊。
Android 內建四組工具:JSONArray、JSONObject、JSONStringer、JSONTokenizer。日常最常用到的是前兩者。
解析之前,先確認目標欄位在哪。以下面這段資料為例,我們要的是 main 裡的溫度:
{ "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 並把整段 JSON 文字交給它:
String in; JSONObject reader = new JSONObject(in);
第二階段,逐層取出各組成部分。由於每個物件的鍵值結構不同,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 | 執行並在裝置上驗證。 |
主活動 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 回傳的溫度是克氏,若要顯示成攝氏,記得做單位換算再呈現。
Android 模擬定位實作教學:權限宣告、狀態偵測與座標注入
想在 App 裡驗證定位功能,卻不方便真的出門跑一條路線?Android 系統本身內建了「模擬位置」機制:只要在開發者選項中指定一支代理程式,系統 GPS 就會回報你自己
Android JSON 解析入門:用 JSONObject 撈出你要的那幾個欄位
JSON(JavaScript Object Notation)自從被提出之後,因為格式輕量、可讀性高,很快就在 Web API 的世界裡取代了 XML 的位置。不管是瀏
Android 使用 ProgressBar 顯示載入中狀態
為什麼需要載入提示?在行動應用中,使用者常常需要等待資料載入。若畫面沒有任何回饋,使用者可能會以為應用沒有反應。此時,不確定型 ProgressBar 是很常見的解法。基
Android 應用多語系實作:本地化字串的資源配置技巧
一支 App 上線後,可能同時被東京、羅馬、柏林的使用者開啟。要讓每個人都用得順,App 就得依照裝置的語言環境調整文字、數字、日期與檔案格式。Android 對這件事有