DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> XML學習教程 >> XML詳解
JSON-lib 實戰指南:Java 物件與 JSON 的雙向轉換
編輯:XML詳解     

在動手寫程式之前,先釐清一個觀念:為什麼 REST 風格與 JSON-lib 這類套件如此契合?從技術角度看,REST 早已不只是「應用在 API 上」這麼單純,它更像是一種設計思維與協定約定。本文會帶你從編碼設定一路走到 JSON 序列化,把背後的眉眉角角講清楚。

先搞定中文亂碼:編碼與 Content-Type

跨窗前後端最常見的坑就是中文亂碼,建議從兩處著手:

1、前後端所有檔案統一採用 UTF-8 編碼。

2、在 Ext 框架的 Ext.onReady 區塊中加入 Ext.lib.Ajax.defaultPostHeader += '; charset=utf-8',可解決 POST 送出時的中文亂碼。

在 JSON-lib 的應用中,還要在 Response 明確指定 Content-Type,Java 端寫法如下:

response.setContentType("text/JSON; charset=utf-8");

這一步能解決 Ext 在畫面顯示後端中文時的亂碼問題。若仍無效,可改試 response.setContentType("application/JSON; charset=utf-8")。要注意這個設定必須放在過濾器之前,理解過濾器的執行順序後就能明白原因。

本文涵蓋重點

  • JSON 序列化的解法與實作
  • 以簡單的 JSON 方法呼叫做示範
  • 處理 JSON 時該留意的細節
  • 使用伺服器端解析器處理 JSON
  • JSON 物件的常用字元與方法

認識 JSON-lib 套件

JSON-lib 是一個能在 beans、collections、maps、Java arrays、XML 與 JSON 之間互相轉換的套件。以下範例示範如何用 JSONObject 建立物件、透過 put() 加入元素,最後把值印出來。使用前記得引入 net.sf.json 套件。

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class JSONObjectSample {

    // 建立 JSONObject 物件
    private static JSONObject createJSONObject(){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "kevin");
        jsonObject.put("Max.score", new Integer(100));
        jsonObject.put("Min.score", new Integer(50));
        jsonObject.put("nickname", "picglet");
        return jsonObject;
    }

    public static void main(String[] args) {
        JSONObject jsonObject = JSONObjectSample.createJSONObject();
        // 輸出 jsonObject 物件
        System.out.println("jsonObject==>" + jsonObject);

        // 判斷輸出物件的類型
        boolean isArray = jsonObject.isArray();
        boolean isEmpty = jsonObject.isEmpty();
        boolean isNullObject = jsonObject.isNullObject();
        System.out.println("isArray:" + isArray + " isEmpty:" + isEmpty + " isNullObject:" + isNullObject);

        // 加入屬性
        jsonObject.element("address", "swap lake");
        System.out.println("加入屬性後的物件==>" + jsonObject);

        // 建立並回傳一個 JSONArray 物件
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(0, "this is a jsonArray value");
        jsonArray.add(1, "another jsonArray value");
        jsonObject.element("jsonArray", jsonArray);
        JSONArray array = jsonObject.getJSONArray("jsonArray");
        System.out.println("回傳一個 JSONArray 物件:" + array);

        // {"name":"kevin","Max.score":100,"Min.score":50,"nickname":"picglet","address":"swap lake",
        //  "jsonArray":["this is a jsonArray value","another jsonArray value"]}

        // 依 key 取得字串
        String jsonString = jsonObject.getString("name");
        System.out.println("jsonString==>" + jsonString);
    }
}

透過 put() 塞入鍵值、element() 追加屬性、getJSONArray() 取回陣列、getString() 取出字串,你就能在 Java 與 JSON 之間自由穿梭。掌握這些基本操作,後續再搭配伺服器端解析器,就能完成完整的資料交換流程。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved