編輯:Android 開發實例
JSON(JavaScript Object Notation)早已是行動裝置與伺服器溝通的首選格式。相較於 XML,它沒有冗長的標籤、沒有命名空間的困擾,解析時也不必來回搬動節點指標,因此幾乎所有開放平臺都改用 JSON 回傳資料。本文從最基礎的結構辨識講起,一路做到一個能查詢城市天氣的 Android 小程式。
Android 自 1.5 起就內含 org.json 套件,四個類別各有分工:
JSONObject:對應一組以花括號包住的鍵值集合,日常開發使用率最高。JSONArray:對應以方括號包住的序列,元素可以是物件、陣列或純量。JSONStringer:以串流方式組出合法 JSON 字串,適合動態產生回應內容。JSONTokener:最底層的詞法分析器,負責把字串切成 token。寫任何一行解析程式之前,請先把 API 回傳的內容攤開來看。以下是一段典型的天氣資料,我們真正想要的是 main 裡的溫度:
{
"sys": { "country": "GB", "sunrise": 1381107633, "sunset": 1381149604 },
"weather": [
{ "id": 711, "main": "Smoke", "description": "smoke", "icon": "50n" }
],
"main": { "temp": 304.15, "pressure": 1009, "humidity": 40 }
}
weather 就是陣列,即使只有一筆,也必須用索引取值。sys 與 main。"country"。先把整段文字交給 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 / getDouble / getInt / getLong(String name):依指定型別取值,型別不符會丟出例外。length():回傳這個物件共有幾組鍵值對。names():回傳包含所有鍵名稱的陣列。optString / optInt 系列:鍵不存在時回傳預設值而不拋例外。面對不可信的外部資料時,這組方法比 getX() 安全得多。這個範例讓使用者輸入城市名稱,程式呼叫天氣服務取得 JSON,解析後把國家、溫度、濕度、氣壓填進四個欄位。實機與模擬器都能執行。
src/MainActivity.java,加入控制項與按鈕事件。res/layout/activity_main.xml 的版面。res/values/strings.xml 補上字串資源。src/HandleJSON.java,負責在背景執行緒抓取並解析資料。AndroidManifest.xml 加上 INTERNET 權限。主活動程式,src/com.example.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.example.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 = "country";
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/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/textV8iew2"
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" />
<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" />
<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" />
<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" />
<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/strings.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:
<?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 按鈕後畫面如下:
按下按鈕的瞬間,程式會連上服務端、下載 JSON、逐層解析,再把欄位填回畫面。
第一,這個服務回傳的溫度是開爾文。若要轉成攝氏,用 攝氏 = 開爾文 − 273.15 即可;304.15 K 大約是 31 °C。
第二,Android 3.0 之後主執行緒禁止發起網路連線,直接這樣寫會收到 NetworkOnMainThreadException。教學用的範例靠 while(obj.parsingComplete); 這種忙等來同步,真實專案請改用背景執行緒搭配回呼、Coroutine,或直接用 OkHttp、Retrofit 這類成熟套件,並記得把端點換成 HTTPS。
Android 仿微信朋友圈九宮格圖片查看器實現
打開微信朋友圈,你會發現一個經典的「九宮格」圖片區域,點擊任意一張圖就能進入大圖查看頁,還支援滑動切換與縮放。這樣的交互幾乎是所有社交類應用的標配。本文就帶你從零實現一個
Android 加載 Spinner 實作指南:ProgressBar 樣式、生命週期與解除時機
在 Android 中,任務的執行進展可以透過載入進度條來呈現。進度條有兩種形態:加載欄與加載微調(spinner)。前者用於能算出百分比的场合,後者則是給那些「還要多久
Android 多語言應用:本地化字串與 values-it 資料夾怎麼用
一支上架的 App,很可能同時被台灣、日本、德國的使用者打開。要讓每個人都看得懂,App 就得依裝置的語言環境,換上對應的文字、數字與格式。這件事在 Android 裡稱
Android JSON 解析實戰:用 JSONObject 把天氣資料變成 App 畫面
JSON(JavaScript Object Notation)早已是行動裝置與伺服器溝通的首選格式。相較於 XML,它沒有冗長的標籤、沒有命名空間的困擾,解析時也不必來