編輯:Android 開發實例
JSON 的全名是 JavaScript Object Notation。它雖然出生於 JavaScript,卻一點也不專屬於它——如今不論哪個語言、哪個平台,都能讀寫這套格式。因為結構淺、標籤少、人眼可讀,它幾乎全面取代了 XML 在 API 回應上的地位。
Android 內建四個 JSON 相關類別:JSONArray、JSONObject、JSONStringer 與 JSONTokenizer。實務上最常用的是 JSONObject,本章就以它為主角。
開始解析前,先確認目標欄位。以下面這段天氣資料為例,我們要的是溫度:
{ "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,把含 JSON 資料的字串交給它:
String in; JSONObject reader = new JSONObject(in);
再依結構逐層取值。遇到內層物件,用 getJSONObject() 取出後再讀欄位:
JSONObject sys = reader.getJSONObject("sys");
country = sys.getString("country");
JSONObject main = reader.getJSONObject("main");
temperature = main.getString("temp");
getJSONObject() 回傳指定鍵的物件,getString() 回傳指定鍵的字串值。此外還有一整組方法可用:
| 編號 | 方法 | 說明 |
|---|---|---|
| 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() | 回傳陣列,內容為此物件所有鍵名。 |
這個範例做出一個天氣查詢 App:使用者輸入城市,程式抓取 JSON 並解析出國家、溫度、濕度與氣壓。
| 步驟 | 做法 |
|---|---|
| 1 | 用 Android Studio 建立專案 JSONParser,Target SDK 與編譯版本採最新 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) {
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.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() : "";
}
}
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/text iew1" 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/text iew1" android:layout_alignParentRight="true" android:ems="10" /> <TextView android:id="@+id/text iew2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/text iew1" android:layout_below="@+id/text iew1" android:layout_marginTop="68dp" android:text="@string/country" android:textAppearance="?android:attr/textAppearanceSmall" /> <EditText android:id="@+id/editText2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/text iew2" android:layout_below="@+id/text iew2" android:ems="10" > <requestFocus /> </EditText> <TextView android:id="@+id/text iew3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/text iew2" android:layout_below="@+id/editText2" android:layout_marginTop="19dp" android:text="@string/temperature" android:textAppearance="?android:attr/textAppearanceSmall" /> <EditText android:id="@+id/editText3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/editText2" android:layout_below="@+id/text iew3" android:ems="10" /> <TextView android:id="@+id/text iew4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/text iew3" android:layout_below="@+id/editText3" android:layout_marginTop="32dp" android:text="@string/humidity" android:textAppearance="?android:attr/textAppearanceSmall" /> <EditText android:id="@+id/editText4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/editText1" android:layout_below="@+id/text iew4" android:ems="10" /> <TextView android:id="@+id/text iew5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/text iew4" android:layout_below="@+id/editText4" android:layout_marginTop="21dp" android:text="@string/pressure" android:textAppearance="?android:attr/textAppearanceSmall" /> <EditText android:id="@+id/editText5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/editText4" android:layout_below="@+id/text iew5" 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="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 加上 android.permission.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>
把 App 裝到 AVD 並啟動,畫面如下:
在位置欄位填入任一城市名稱,這裡以紐約為例:
按下 Weather,App 便會連線抓取 JSON 並解析,把結果填進各欄位。
要注意的是,這類服務回傳的溫度是凱氏。想轉成比較熟悉的攝氏,減掉 273.15 即可。
Android 進度轉圈元件教學:Spinner 顯示與隱藏
在 Android 介面中,進度轉圈元件常用於提示資料正在載入。它屬於不確定進度條的一種,適合不知道完成時間的工作。 顯示與隱藏 透過 setVisibility 可以控
MediaPlayer 音訊與視訊播放:搭配 SurfaceView 與 SeekBar 的完整實作
前面的文章把 Android 介面的入門技術介紹得差不多了,相信讀者對常見的 Layout 與 View 都已經有概念。接下來不再談介面,改針對具體功能逐一深入。 本文
Android 為 WebView 加上頂部進度條的實作
寫這篇純粹做備忘,示範一個在 WebView 上方顯示載入進度條的簡易寫法。 效果如下: 版面配置 由上到下依序是:重新載入按鈕、進度條、WebView。用 Rela
Android 在地化實務:從 strings.xml 到語言切換
在地化的意義在地化不只是翻譯文字,也包括讓應用符合不同地區使用者的閱讀習慣。最常見的做法,是將畫面文字集中管理,並依語言提供不同資源。資源資料夾結構預設字串通常放在 re