Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 中 JSON 資料的讀取與建立實作

編輯:關於 Android 程式設計

JSON(JavaScript Object Notation)是一種輕量級的資料交換格式,可讀性高、撰寫方便,主流語言都有完整的支援,因此成為跨平台資料交換的常見選擇。它的結構只有兩種:Name/Value Pairs(無序的鍵值對,類似 Map、Hash table,在 Android 中與 Bundle 有相似之處)與 Array(有序的資料列表)。

以下示範如何把 JSON 檔放進 assets、讀取出來解析,以及在程式中動態建立 JSON。

一、建立 assets 目錄

在 Android Studio 中建立 assets 資料夾用來存放 JSON 檔。1.3 版以後預設專案並不會自動產生 assets,需要自行新增:在 app/src/main/ 上按右鍵 → New → Folder → Assets Folder。

建立完成後,在目錄中新增一個 Text.json。

二、讀取 assets 中的 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。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved