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

Android 中的 JSON 雙向轉換:用 JSONObject 與 JSONArray 打包與解析資料

編輯:關於 Android 程式設計

Android SDK 內建的 org.json 套件提供了 JSONObject 與 JSONArray,足以完成兩件最常見的工作:把集合或一般物件序列化成 JSON 字串,以及把 JSON 字串還原成集合或物件。本文用一個可運行的完整範例把兩個方向都走一遍。

一、準備資料與版面

版面放四顆按鈕,分別負責:普通物件轉 JSON、集合轉 JSON、解析普通 JSON、解析含集合的 JSON;下方一個 TextView 顯示結果。

public class MainActivity extends Activity implements OnClickListener {

    private Button button1, button2, button3, button4;
    private TextView textView;
    private List<UserBean> userBeans;   // 待轉換的集合
    private JSONObject object;           // 處理單一物件
    private JSONObject object2;
    private JSONArray jsonArray;         // 處理集合/陣列
    private String jsonString;           // 含集合的 JSON 字串
    private String jsonString2;          // 不含集合的 JSON 字串

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        initView();
        initDate();
        setListener();
    }

    private void initView() {
        button1 = (Button) findViewById(R.id.bt1);
        button2 = (Button) findViewById(R.id.bt2);
        button3 = (Button) findViewById(R.id.bt3);
        button4 = (Button) findViewById(R.id.bt4);
        textView = (TextView) findViewById(R.id.text);
    }

    private void initDate() {
        userBeans = new ArrayList<UserBean>();
        UserBean a = new UserBean();
        a.setUserId(1);
        a.setUserName("hck");
        userBeans.add(a);

        UserBean b = new UserBean();
        b.setUserId(2);
        b.setUserName("蝌蚪");
        userBeans.add(b);
    }

    private void setListener() {
        button1.setOnClickListener(this);
        button2.setOnClickListener(this);
        button3.setOnClickListener(this);
        button4.setOnClickListener(this);
    }

二、集合 → JSON 字串

做法是外層一個 JSONObject、內層用 JSONArray 裝多個 JSONObject,最後一起 toString()。

private void changeArrayDateToJson() {
    jsonArray = new JSONArray();
    object = new JSONObject();

    for (int i = 0; i < userBeans.size(); i++) {
        object2 = new JSONObject();   // 每個 UserBean 對應一個 JSONObject
        try {
            // JSONObject 的用法與 Map 類似,以鍵值形式存放資料
            object2.put("userId", userBeans.get(i).getUserId());
            object2.put("userName", userBeans.get(i).getUserName());
            jsonArray.put(object2);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    try {
        object.put("userDate", jsonArray);
        // 這裡還可以塞入一般欄位,讓結果同時包含集合與普通資料
        // object.put("time", "2013-11-14");
    } catch (JSONException e) {
        e.printStackTrace();
    }

    jsonString = object.toString();
    textView.setText(jsonString);
}

三、普通物件 → JSON 字串

private void changeNotArrayDateToJson() {
    object = new JSONObject();
    try {
        // "userId" 相當於 Map 的 key,1 就是對應的 value
        object.put("userId", "1");
        object.put("userName", "hck");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    jsonString2 = object.toString();
    textView.setText(jsonString2);
}

四、JSON 字串 → 集合

private void changeJsonToData1() {
    StringBuilder sb = new StringBuilder();
    List<UserBean> bList = new ArrayList<UserBean>();
    try {
        object = new JSONObject(jsonString);
        // 以 key 取出內層的 JSONArray
        jsonArray = object.getJSONArray("userDate");
        for (int i = 0; i < jsonArray.length(); i++) {
            object = jsonArray.getJSONObject(i);
            UserBean userBean = new UserBean();
            userBean.setUserId(object.getInt("userId"));
            userBean.setUserName(object.getString("userName"));
            bList.add(userBean);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    for (int i = 0; i < bList.size(); i++) {
        sb.append("用戶id:").append(bList.get(i).getUserId())
          .append(" ").append("用戶名字:").append(bList.get(i).getUserName());
    }
    textView.setText(sb.toString().replace("null", ""));
}

五、JSON 字串 → 單一物件

private void changeJsonToData2() {
    try {
        object = new JSONObject(jsonString2);
        String userName = object.getString("userName");
        String userIdString = object.getString("userId");
        textView.setText("用戶id" + userIdString + "用戶名字:" + userName);
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

六、事件綁定與防呆

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.bt1:
            changeNotArrayDateToJson();
            break;
        case R.id.bt2:
            changeArrayDateToJson();
            break;
        case R.id.bt3:
            if (jsonString2 == null || "".equals(jsonString2)) {
                Toast.makeText(this, "請先點擊第 1 個按鈕把資料轉成 JSON", Toast.LENGTH_LONG).show();
                return;
            }
            changeJsonToData2();
            break;
        case R.id.bt4:
            if (jsonString == null || "".equals(jsonString)) {
                Toast.makeText(this, "請先點擊第 2 個按鈕把資料轉成 JSON", Toast.LENGTH_LONG).show();
                return;
            }
            changeJsonToData1();
            break;
    }
}

七、實務上的幾點建議

  • 先想清楚要不要自己拼 JSON。如果資料來源本身就是物件,直接用 Gson 或 Moshi 一行 toJson() / fromJson() 就能完成同樣的事,還能免掉大量手寫 put/get 的樣板程式與型別錯誤風險。
  • 注意型別轉換的嚴格性。getInt() 遇到字串 "1" 在部分實作中會拋 JSONException;若後端型別不穩定,建議改用 optInt(key, default) 或 optString() 這類容錯版本。
  • 欄位缺失不要讓它炸掉。getXxx() 找不到 key 會拋例外,optXxx() 則回傳預設值。解析外部資料時,後者通常更安全。
  • 別忘了 UTF-8。伺服器回傳的位元組要明確指定編碼(new String(bytes, "UTF-8")),否則中文容易變成亂碼。
  • 避免在主線程做大量解析。資料量稍大就應該放到背景執行緒,或使用 Kotlin 的協程搭配 withContext(Dispatchers.IO)。

把「物件 → 字串」與「字串 → 物件」這兩個方向都跑通一次,之後不論是與 REST API 對接,還是做本地快取序列化,都能得心應手。

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