編輯:Android 開發實例
JSON 的全名是 JavaScript Object Notation,但它早已擺脫 JavaScript 的框架,成為跨語言、跨平台的資料交換標準。它是 XML 之外最主流的替代方案:沒有冗長的封閉標籤,檔案更小、可讀性更好、解析更快。本章要說明如何在 Android 上讀取 JSON 並取出需要的欄位。
Android 內建四個 JSON 類別:JSONObject、JSONArray、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 }
}
可以看到 temp 並不在最外層,而是被包在 main 裡面。解析時必須先取得 main 這個子物件,再往內取 temp。
| 要素 | 說明 |
|---|---|
Array [ ] | 方括號代表陣列,可包含多個物件。 |
Object { } | 大括號代表物件,由多組鍵值對構成。 |
| Key | 物件中的鍵,必定是字串。鍵與值配對,才形成一個完整的物件。 |
| Value | 鍵對應的值,可能是字串、整數、double 或其他型別。 |
先把整段 JSON 文字交給 JSONObject:
String in; JSONObject reader = new JSONObject(in);
再依結構逐層取出。遇到子物件用 getJSONObject,取字串用 getString:
JSONObject sys = reader.getJSONObject("sys");
country = sys.getString("country");
JSONObject main = reader.getJSONObject("main");
temperature = main.getString("temp");
依型別不同,還有下列選擇:
| 方法 | 說明 |
|---|---|
get(String name) | 回傳 Object 型別的值。 |
getBoolean(String name) | 回傳指定鍵的布林值。 |
getDouble(String name) | 回傳 double 值。 |
getInt(String name) | 回傳整數值。 |
getLong(String name) | 回傳 long 值。 |
length() | 回傳此物件中鍵值對的數量。 |
names() | 回傳包含所有鍵名稱的陣列。 |
這個範例示範如何使用 JSONObject:做出一個天氣應用,讓使用者輸入城市,程式呼叫天氣服務 API 取得 JSON 並解析顯示。可在實機或模擬器執行。
| 步驟 | 做法 |
|---|---|
| 1 | 用 Android Studio 建立專案 JSONParser,Target SDK 選最新可得版本以使用較新 API。 |
| 2 | 修改 src/MainActivity.java 加入必要程式碼。 |
| 3 | 修改 res/layout/activity_main.xml 加入對應元件。 |
| 4 | 修改 res/values/string.xml 加入字串。 |
| 5 | 新增 src/HandleJSON.java,負責抓取與解析 JSON。 |
| 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) {
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/textViedw1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignParentTop="true"
android:layout_marginTop="15dp" android:text="@string/location" />
<EditText android:id="@+id/editText1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:ems="10" />
<TextView android:id="@+id/textViedw2" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="@string/country" />
<EditText android:id="@+id/editText2" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:ems="10" />
<TextView android:id="@+id/textViedw3" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="@string/temperature" />
<EditText android:id="@+id/editText3" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:ems="10" />
<TextView android:id="@+id/textViedw4" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="@string/humidity" />
<EditText android:id="@+id/editText4" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:ems="10" />
<TextView android:id="@+id/textViedw5" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="@string/pressure" />
<EditText android:id="@+id/editText5" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:ems="10" />
<Button android:id="@+id/button1" android:layout_width="wrap_content"
android:layout_height="wrap_content" 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,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-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 並解析,把結果填回畫面。再次提醒:這個服務回傳的溫度是克氏(Kelvin),若要顯示成攝氏,記得做單位換算。
Android 本地化:讓同一支 App 在不同語言環境下說不同的話
一支上架的 App,可能同時被義大利米蘭的使用者、日本東京的使用者、德國柏林的用戶打開。若所有文字都寫死在程式碼裡,海外市場就等於放棄。Android 對這件事有非常漂亮
Android MediaPlayer 音訊播放實戰
Android 提供了多種控制音訊與影片播放的方式,不論是播放本機檔案或串流來源都能應付,而其中最典型的做法就是使用 MediaPlayer 類別。 Android 透過
Android 多語系本地化:strings.xml 與 values-it 設定
Android 的本地化主要是讓同一套 App 能依裝置語言顯示不同文字。最簡單的做法,是把畫面上會變動的文字放到 string.xml,再針對各語言建立對應資源。 建立
Android 五種資料儲存方式全解析:SharedPreferences、檔案、SQLite、ContentProvider 與網路
資料儲存是開發中最頻繁面對的課題之一。Android 提供了多種互補的機制,本文逐一說明五種主要方式,並附上各自的關鍵程式碼與適用情境。 SharedPreferen