編輯:關於 Android 程式設計
JSON(JavaScript Object Notation)是一種輕量級的資料交換格式,具備可讀性佳、撰寫方便的特性。因為格式簡單通用,主流語言幾乎都提供了完整的支援方案(有點類似正則表達式的普及程度),因此特別適合在不同平台之間傳遞資料。它採用相容性極高的純文字格式,語法行為則近似 C 語言家族。
JSON 的結構只有兩種基礎型態:
(1) Name/Value Pairs(無序):也就是我們熟悉的 Keyed list、Hash table、Dictionary、Associative array。在 Android 平台中,Bundle 在行為上有幾分相似。
(2) Array(有序):一組依序排列的資料列表。
物件是無序的 name/value 集合:
{ name: value , name: value , name: value .... }
例如:
{ "name": "小豬", "age": 20 }
陣列是值的有序集合:
[ value , value , value ...... ]
值可以是括在雙引號中的字串、數值、true、false、null、物件或陣列,而且這些結構可以任意嵌套。
字串是由雙引號包圍的任意數量 Unicode 字元集合,使用反斜線跳脫;單一字元也就是長度為一的字符串。跳脫字元包括:\" \\ \/ b f n r t u。
陣列裡包含物件:
[ {"id":1,"name":"小豬","age":22} , {"id":2,"name":"小貓","age":23} , ....... ]
物件中包含陣列(一個陣列、兩個純量欄位):
{"root":[{"id":"001","name":"小豬"},{"id":"002","name":"小貓"},{"id":"003","name":"小狗"}],
"total":3,
"success":true
}
物件嵌套子物件,子物件再嵌套陣列:
{"calendar":
{"calendarlist":
[
{"id":"001","name":"小豬"},
{"id":"002","name":"小貓"}
]
}
}
總之,格式變化多端,可以彼此自由嵌套。
Android 內建了四個與 JSON 相關的類別與一個例外類別:
JSONArray、JSONObject、JSONStringer、JSONTokener、JSONException
這是系統中關於 JSON 定義的基本單元,內部保存一對對的 Key/Value。
對外部輸出(呼叫 toString() 得到的結果)而言,它表現為一個標準字符串,最外層由大括號包裹,Key 與 Value 之間以冒號分隔,例如:
{ "JSON" : "Hello, World" }
而對內部的操作方式略有不同,例如建立實例並用 put() 加入數值:
new JSONObject().put("JSON", "Hello, World!");
Value 的型別可以是 Boolean、JSONArray、JSONObject、Number、String,或預設值 JSONObject.NULL。
取值方法有兩種,差別在容錯行為:
get():確定數值存在時使用,否則當找不到對應 Key 時會拋出例外。
opt():相對寬鬆,取不到指定數值時會回傳預設值而不拋出例外。寫網路相關程式時,這個方法通常比較省心。
代表一組有序的數值。轉成字串輸出時以方括號包裹、逗號分隔,例如 [value1,value2,value3]。這個類別同樣具備查詢行為,get() 與 opt() 都能透過 index 索引回傳指定位元組的數值,put() 則用於新增或替換數值。值的型別範圍與 JSONObject 相同。
根據官方說法,這個類別能快速且便利地建立 JSON text,最大的優點是可以避免因為格式寫錯而導致的執行期異常——它會嚴格按照 JSON 語法規則來組裝內容。每個 JSONStringer 實例只能對應產生一份 JSON text。
String myString = new JSONStringer()
.object()
.key("name")
.value("小豬")
.endObject()
.toString();
結果就是一份標準格式的 JSON text:{ "name" : "小豬" }。其中 object() 與 endObject() 必須成對使用,負責替數值加上物件邊界;陣列則對應 array() 與 endArray()。
這是系統提供給 JSONObject 與 JSONArray 建構子使用的解析類別,能從來源字符串中抽取出數值資訊。
JSON.org 系列類別所拋出的例外資訊。
public static JSONObject getJSON(Map map) {
Iterator iter = map.entrySet().iterator();
JSONObject holder = new JSONObject();
while (iter.hasNext()) {
Map.Entry pairs = (Map.Entry) iter.next();
String key = (String) pairs.getKey();
Map m = (Map) pairs.getValue();
JSONObject data = new JSONObject();
try {
Iterator iter2 = m.entrySet().iterator();
while (iter2.hasNext()) {
Map.Entry pairs2 = (Map.Entry) iter2.next();
data.put((String) pairs2.getKey(), (String) pairs2.getValue());
}
holder.put(key, data);
} catch (JSONException e) {
Log.e("Transforming", "There was an error packaging JSON", e);
}
}
return holder;
}
以下是一個可直接套用的工具類,示範如何下載資料並分別處理「陣列形態」、「物件形態」與「巢狀複雜形態」的 JSON。
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
import android.util.Log;
public class JSON {
/**
* 取得「陣列形態」的 JSON 資料
* 資料形式:[{"id":1,"name":"小豬"},{"id":2,"name":"小貓"}]
*/
public static List<Map<String, String>> getJSONArray(String path) throws Exception {
String json = null;
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
Map<String, String> map = null;
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5 * 1000); // 逾時 5 秒,單位毫秒
conn.setRequestMethod("GET");
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
byte[] data = readStream(is);
json = new String(data);
// 資料形式:[{"id":1,"name":"小豬","age":22},{"id":2,"name":"小貓","age":23}]
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject item = jsonArray.getJSONObject(i);
int id = item.getInt("id");
String name = item.getString("name");
map = new HashMap<String, String>();
map.put("id", id + "");
map.put("name", name);
list.add(map);
}
}
return list;
}
/**
* 取得「物件形態」的 JSON 資料
* 資料形式:{"total":2,"success":true,
* "arrayData":[{"id":1,"name":"小豬"},{"id":2,"name":"小貓"}]}
*/
public static List<Map<String, String>> getJSONObject(String path) throws Exception {
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
Map<String, String> map = null;
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
byte[] data = readStream(is);
String json = new String(data);
JSONObject jsonObject = new JSONObject(json);
int total = jsonObject.getInt("total");
Boolean success = jsonObject.getBoolean("success");
Log.i("abc", "total:" + total + " | success:" + success);
JSONArray jsonArray = jsonObject.getJSONArray("arrayData");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject item = jsonArray.getJSONObject(i);
int id = item.getInt("id");
String name = item.getString("name");
map = new HashMap<String, String>();
map.put("id", id + "");
map.put("name", name);
list.add(map);
}
}
return list;
}
/**
* 取得型別較複雜的 JSON 資料
* 資料形式:
* {"name":"小豬",
* "age":23,
* "content":{"questionsTotal":2,
* "questions": [ { "question": "what's your name?", "answer": "小豬"},
* {"question": "what's your age", "answer": "23"} ]
* }
* }
*/
public static List<Map<String, String>> getJSON(String path) throws Exception {
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
Map<String, String> map = null;
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
byte[] data = readStream(is);
String json = new String(data);
JSONObject jsonObject = new JSONObject(json);
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
Log.i("abc", "name:" + name + " | age:" + age);
// 取得物件中的物件
JSONObject contentObject = jsonObject.getJSONObject("content");
String questionsTotal = contentObject.getString("questionsTotal");
Log.i("abc", "questionsTotal:" + questionsTotal);
// 取得物件中的陣列
JSONArray contentArray = contentObject.getJSONArray("questions");
for (int i = 0; i < contentArray.length(); i++) {
JSONObject item = contentArray.getJSONObject(i);
String question = item.getString("question");
String answer = item.getString("answer");
map = new HashMap<String, String>();
map.put("question", question);
map.put("answer", answer);
list.add(map);
}
}
return list;
}
/** 把輸入流轉成位元組陣列 */
public static byte[] readStream(InputStream inputStream) throws Exception {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
bout.write(buffer, 0, len);
}
bout.close();
inputStream.close();
return bout.toByteArray();
}
}
三個方法的骨架其實一致:建立連線 → 設定逾時與請求方式 → 判斷回應碼是否為 200 → 讀取串流轉字串 → 依 JSON 形態選擇用 JSONArray 還是 JSONObject 作為解析入口。真正的差異只在最後的解析層級,遇到巢狀結構就一層一層往下取物件與陣列即可。
Android 屬性動畫進階:TypeEvaluator、ObjectAnimator 與自訂 View 實作
補間動畫與屬性動畫的差異 補間動畫主要改變 View 的顯示效果,例如平移、縮放、旋轉與透明度,但實際屬性未必改變。屬性動畫則可直接修改物件的屬性值,因此更靈活。 Typ
Android滑動衝突解決案例:外部攔截法與Scroller詳解
前幾篇博客中,我測試了View事件分發機制的一些知識點。理解事件分發機制的目的,是為了更好地掌握View中事件的傳遞過程,進而針對滑動衝突制定有效的解決措施。今天我們就通
Android 開發步步為營(35):GridView 的用法
之前在 ASP.NET 開發中也用過 GridView,發現 Android 裡也有這麼一個控制項,用法頗為相似——都是透過 Adapter 把資料綁定到控制項上再展示出
Android View 繪製流程解析:measure、layout 與 draw
Android 的 View 繪製流程可以概括為 measure、layout 與 draw 三個階段。當 Activity 取得焦點後,系統會從根節點開始,對整棵 Vi