編輯:關於 Android 程式設計
JSON(JavaScript Object Notation)是一種輕量級的資料交換格式,具備良好的可讀性與易於撰寫的特性。由於採用兼容性極高的文字格式,並獲得當今大多數語言的支持,因此能在不同平台之間進行資料交換。
JSON 主要由兩種結構組成:
(1) Name/Value Pairs(無序):類似 Keyed list、Hash table、Dictionary 與關聯陣列,在 Android 中 Bundle 在某種程度上也有相似行為。
(2) Array(有序):一組有序的資料列表。
物件(Object)是無序的 Name/Value 集合,例如 {"name":"小豬","age":20}。
陣列(Array)是值的有序集合,例如 [value, value, value],值可以是字串、數值、true、false、null、物件或陣列,且可任意嵌套。
Android 內建四個與 JSON 相關的類與一個例外:JSONArray、JSONObject、JSONStringer、JSONTokener、JSONException。
JSONObject:JSON 定義的基本單元,包含一組 Key/Value。對外輸出的標準字串以大括號包裹、Key 與 Value 以冒號分隔;取值有兩種方式:get() 在找不到 Key 時會拋出例外,opt() 則在取不到值時回傳預設值而不拋例外。Value 型別包含 Boolean、JSONArray、JSONObject、Number、String 或 JSONObject.NULL。
JSONArray:代表一組有序值,轉字串時以方括號包裹、逗號分隔。同樣提供 get() 與 opt() 以 index 取值,put() 用來添加或替換。
JSONStringer:幫助快速便捷地建立 JSON text,能自動依 JSON 語法規則產生結果,避免格式錯誤。每個實例只能建立一段 JSON text。例如:
String myString = new JSONStringer().object().key("name").value("小豬").endObject().toString();
其中 object() 與 endObject() 必須成對使用以建立物件邊界,array() 與 endArray() 則用於陣列。
JSONTokener:供 JSONObject 與 JSONArray 建構子解析 JSON 來源字串。
JSONException: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);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
byte[] data = readStream(is);
json = new String(data);
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);
}
}
for (Map<String, String> list2 : list) {
String id = list2.get("id");
String name = list2.get("name");
Log.i("abc", "id:" + id + " | name:" + name);
}
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);
}
}
for (Map<String, String> list2 : list) {
String id = list2.get("id");
String name = list2.get("name");
Log.i("abc", "id:" + id + " | name:" + name);
}
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);
}
}
for (Map<String, String> list2 : list) {
String question = list2.get("question");
String answer = list2.get("answer");
Log.i("abc", "question:" + question + " | answer:" + answer);
}
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();
}
}
透過這三種範例,就能應付絕大多數 RESTful 介面回傳的 JSON 資料結構了。
關於 RACCommand 的思考:源碼級別的完整解讀
簡介 ReactiveCocoa 為各類控件加上「信號」特性,做法是透過 category。例如在 UIButton+RACCommandSupport.h 中: @c
Android 自動化測試 UiAutomator(三):用腳本自動比對測試截圖
系列回顧:本系列從開發者角度介紹 UiAutomator 的使用,共三篇——基礎入門、技巧篇,以及這一篇的比較工具篇:比對測試截圖。 1. 適用範圍 本文的方法適用於所
設計模式筆記:適配器模式(Adapter)入門與實作
適配器模式是我們日常開發裡出現頻率最高、也最容易埋雷的模式。從早期的 ListView、GridView 到現在的 RecyclerView,都少不了一個 Adapter
Android 快速註冊頁與驗證碼的實作教學
本文示範一個簡潔的註冊頁面,包含用戶名、密碼、密碼確認、暱稱、性別單選,以及一組可點擊刷新的驗證碼。整體以 ScrollView 搭配 LinearLayout 與多個