編輯:關於 Android 程式設計
JSON(JavaScript Object Notation)是一種輕量級的資料交換格式,可讀性高、撰寫方便,主流語言都有完整的支援,因此成為跨平台資料交換的常見選擇。它的結構只有兩種:Name/Value Pairs(無序的鍵值對,類似 Map、Hash table,在 Android 中與 Bundle 有相似之處)與 Array(有序的資料列表)。
以下示範如何把 JSON 檔放進 assets、讀取出來解析,以及在程式中動態建立 JSON。
在 Android Studio 中建立 assets 資料夾用來存放 JSON 檔。1.3 版以後預設專案並不會自動產生 assets,需要自行新增:在 app/src/main/ 上按右鍵 → New → Folder → Assets Folder。

建立完成後,在目錄中新增一個 Text.json。
Eclipse 專案的做法:
InputStreamReader(getAssets().open("Text.json"), "UTF-8");
Android Studio 專案則可用 ClassLoader:
JsonLearn.this.getClass().getClassLoader().getResourceAsStream("assets/" + "Text.json");
兩者都回傳 InputStream,後續處理方式相同。
畫面上兩個按鈕,分別負責「讀取」與「建立」JSON,結果顯示在 TextView 中。

package activity.cyq.datalrearn;
import android.support.v.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class JsonLearn extends AppCompatActivity {
private TextView writeText, readText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_json_learn);
readText = (TextView) findViewById(R.id.readJsonText);
writeText = (TextView) findViewById(R.id.writeJsonText);
/* 讀取 JSON 資料 */
findViewById(R.id.readJsioBtn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 取得 assets 下的 Text.json,以串流形式回傳
InputStream is = JsonLearn.this.getClass().getClassLoader()
.getResourceAsStream("assets/" + "Text.json");
InputStreamReader streamReader = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(streamReader);
String line;
StringBuilder stringBuilder = new StringBuilder();
try {
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
reader.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
JSONObject person = new JSONObject(stringBuilder.toString());
JSONArray infArray = person.getJSONArray("inf");
for (int i = 0; i < infArray.length(); i++) {
JSONObject inf = infArray.getJSONObject(i);
readText.append("name:" + inf.getString("name") + "\n");
readText.append("IdCard:" + inf.getString("IdCard"));
readText.append("age:" + inf.getInt("age"));
readText.append("married:" + inf.getBoolean("married"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
/* 建立 JSON 資料並顯示 */
findViewById(R.id.writeJsioBtn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
JSONObject inf = new JSONObject();
inf.put("number", 2);
JSONArray array = new JSONArray();
JSONObject arr1 = new JSONObject();
arr1.put("name", "張三");
arr1.put("age", 22);
arr1.put("IdCard", "XC");
arr1.put("married", true);
JSONObject arr2 = new JSONObject();
arr2.put("name", "李四");
arr2.put("age", 25);
arr2.put("IdCard", "@DC");
arr2.put("married", true);
array.put(0, arr1);
array.put(1, arr2);
inf.put("inf", array);
writeText.setText(inf.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
對應的 Text.json 內容大致如下:
{
"inf": [
{ "name": "張三", "IdCard": "XC", "age": 22, "married": true },
{ "name": "李四", "IdCard": "@DC", "age": 25, "married": true }
]
}
讀取時用 JSONObject 配合 getJSONArray() 逐筆取出,再依欄位型別分別呼叫 getString()、getInt()、getBoolean();建立時則反過來用 put() 組裝,最後 toString() 輸出。若欄位可能不存在,建議改用 optString()、optInt() 這類容錯版本,避免 JSONException。
實際專案中,Android 內建的 org.json 已足夠應付簡單情境;若處理複雜結構或需要效能,可考慮 Gson(Google)或 Fast-Json(阿里)這類第三方 API。
Android 入門實作:打造一個文件夾管理器(二)檔案操作與批次處理
上一篇我們已經把文件夾清單呈現出來了。這一篇要為清單子項加上事件與操作能力:點擊檔案就開啟,點擊文件夾就進入並遍歷,以此類推直到抵達最後一層。 FileOpreatio
用frame動畫打造 Android 蝸牛風格進度條
好的介面細節能顯著提升使用者的第一印象。本文實作一個以蝸牛爬行動畫作為「滑塊」的進度條,讓等待過程更有趣味性。 一、準備frame動畫資源 <?xml versi
Android 學習筆記(四):常用基本控制項與視圖整理
一、文字、按鈕與輸入框 這三者關係密切,先看它們的繼承結構: TextView 是它們的共同祖先,最基礎也最常用: android:text=文本 android:t
為Android Studio打造自定義Gradle插件的完整教程
Google已經建議Android開發全面轉向Android Studio,而Android Studio使用gradle進行編譯打包。既然gradle功能龐大,那不如動