編輯:Android 開發實例
JSON(JavaScript Object Notation)是一種輕量級的資料交換格式,具備良好的可讀性與易於撰寫的特性。由於業界主流技術都為它提供了完整解決方案(有點像當年正則表達式的普及),使它能跨平台進行資料交換。它採用相容性極高的文字格式,同時也具備類似 C 語言體系的一些行為。
(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。
JSONObject:系統中 JSON 定義的基本單元,包含一對 Key/Value。對外輸出(呼叫 toString)時呈現為標準字串(最外層以大括號包裹、Key 與 Value 以冒號分隔);對內操作則以 put() 等方法添加數值。Value 類型可為 Boolean、JSONArray、JSONObject、Number、String 或預設值 JSONObject.NULL。取值有兩種方法:get() 在確定數值存在時使用,否則找不到 Key 會拋出例外;opt() 較為靈活,取不到時會回傳預設值而不拋例外。
JSONArray:代表一組有序數值,輸出時以方括號包裹、以逗號分隔。get() 與 opt() 都可透過 index 回傳指定值,put() 則用來添加或替換。value 類型同樣可為 Boolean、JSONArray、JSONObject、Number、String 或 JSONObject.NULL。
JSONStringer:幫助快速便捷地建立 JSON text,最大優點是自動依 JSON 語法規則產生,能減少格式錯誤導致的異常。每個 JSONStringer 實例只能對應建立一個 JSON text:
String myString = new JSONStringer().object().key("name").value("小豬").endObject().toString();
其中 object() 與 endObject() 必須成對使用以給數值加上物件邊界;針對陣列則有 array() 與 endArray()。
JSONTokener:供 JSONObject 與 JSONArray 的建構子解析 JSON source string,可從中擷取數值。
JSONException:JSON.org 類別拋出的例外。
用 JSONObject 儲存 Map 型別數值:
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);
}
}
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數據(多層嵌套)
*/
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();
}
}
Android 學習筆記:單元測試實例完整解析
本文以實例方式,完整說明如何在 Android 專案中設定並執行單元測試。測試是開發流程中不可或缺的一環,透過 JUnit 框架能有效驗證程式的正確性。第一步:修改 An
Android Spinner 載入進度條實作
在 Android 中,可以透過進度條向使用者顯示某項任務的執行進展。進度條主要分為兩種形態:進度列與旋轉式載入指示器(Spinner)。本章將聚焦於後者。 Spinne
Android 自訂 View 實作:用 Canvas 畫出可互動的正弦波
正弦波是訊號處理與物理課程的常客,但把它畫在 Android 畫面上,其實是一次很好的 Canvas 與自訂 View 練習。本文從零示範:輸入頻率、相位與振幅,按下滑鈕
Android 進階:用 MediaPlayer 播放網絡視頻
此前我們講解過用 MediaPlayer 播放網絡音頻,重點在於網絡音頻的緩衝與進度條控制。本文在此基礎上,進一步探討如何用 MediaPlayer 播放網絡視頻。相比播