在 Ajax 架構下,伺服器端視圖層從「生成完整 HTML」轉型為「輸出結構化資料」,Java 物件序列化策略的選擇直接決定前後端協作效率、頻寬成本與客戶端處理複雜度。本文系統對比五大序列化技術路線:手工 XML、XML 綁定框架(代碼生成/映射)、模板引擎、純文本、JSON,提供適用場景決策矩陣與實戰代碼範例。

資料模型:Customer → Orders → Items
// Order.java
public Element toXML() {
Element elOrder = new Element("order");
elOrder.setAttribute("id", id);
elOrder.setAttribute("cost", getFormattedCost());
elOrder.addContent(new Element("date").setText(date));
Element elItems = new Element("items");
for (Item item : items) {
elItems.addContent(item.toXML()); // 遞迴委派
}
elOrder.addContent(elItems);
return elOrder;
}
// Servlet 輸出
Document doc = new Document(customer.toXML());
res.setContentType("application/xml");
new XMLOutputter(Format.getPrettyFormat()).output(doc, res.getWriter());
優點: 簡單直接、無額外依賴、任意物件圖幾行代碼搞定
致命缺陷: 模型與視圖強耦合 — 每類別只能有一種 XML 表現,導致:
<!-- order-history.jsp --%>
<?xml version="1.0"?><%@ page contentType="application/xml" %>
<%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core" %>
<orderHistory username="${customer.username}">
<c:forEach var="order" items="${customer.orders}">
<order id="${order.id}" cost="${order.formattedCost}">
<date>${order.date}</date>
<items>
<c:forEach var="item" items="${order.items}">
<item id="${item.id}">
<name><c:out value="${item.name}" escapeXml="true"/></name>
<price>${item.formattedPrice}</price>
</item>
</c:forEach>
</items>
</order>
</c:forEach>
</orderHistory>
優點: 視圖完全可定製,同一模型可生成訂單歷史/商品搜尋/行動版等多種 XML,邏輯在模板而非 Java 代碼
挑戰: 開發者需自行確保 XML 結構正確(標籤配對、實體轉義),無 Schema 驗證保護(開發期可補強)
true、42、item1,item2,item3responseText.match(/<date>(.*?)<\/date>/))// Order.java 使用 org.json
public JSONObject toJSONObject() {
JSONObject json = new JSONObject();
json.put("id", id);
json.put("cost", getFormattedCost());
json.put("date", date);
JSONArray jsonItems = new JSONArray();
for (Item item : items) {
jsonItems.put(item.toJSONObject());
}
json.put("items", jsonItems);
return json;
}
// Servlet 輸出
res.setContentType("application/json");
res.getWriter().print(customer.toJSONObject().toString());
客戶端處理 — 輕鬆愉快:
var customer = eval("(" + req.responseText + ")"); // 或 JSON.parse()
var firstItemName = customer.orders[customer.orders.length-1].items[0].name;
優勢對比:
| 維度 | XML + DOM | JSON |
|---|---|---|
| 解析速度 | 慢(建構 DOM 樹) | 極快(原生物件圖) |
| 客戶端代碼 | 冗長(getElementsByTagName...) | 極簡(點號存取) |
| 空白節點干擾 | 嚴重 | 無 |
| 頻寬 | 較大(標籤重複) | 較小(鍵值對) |
| 工具生態 | 成熟 | 極其豐富 |

六大維度評分表(1-5 分)
| 技術 | 可擴展性 | 整合容易度 | Java API 友善度 | 輸出控制力 | 視圖靈活性 | 客戶端存取 | 推薦指數 |
|---|---|---|---|---|---|---|---|
| 手工 XML | 2 | 5 | 3 | 5 | 1 | 2 | ⭐⭐ |
| 代碼生成綁定 | 5 | 2 | 2 | 3 | 1 | 3 | ⭐⭐⭐ |
| 映射綁定 | 4 | 4 | 4 | 3 | 2 | 3 | ⭐⭐⭐⭐ |
| 模板引擎 | 4 | 3 | 4 | 5 | 5 | 3 | ⭐⭐⭐⭐⭐ |
| 純文本 | 1 | 5 | 5 | 2 | 1 | 5 | ⭐⭐ |
| 手工 JSON | 2 | 4 | 4 | 4 | 1 | 5 | ⭐⭐⭐⭐ |
| 自動 JSON (Jackson/Gson) | 5 | 5 | 5 | 4 | 3 | 5 | ⭐⭐⭐⭐⭐ |
// 僅需在 POJO 加上註解,零樣板碼
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"id", "name", "price", "description"})
public class Item {
private String id;
private String name;
private String description;
private BigDecimal price;
// Getter/Setter 或 public 欄位
}
// Spring MVC 自動處理
@GetMapping(value = "/api/items", produces = MediaType.APPLICATION_JSON_VALUE)
public List- getItems() { return itemService.findAll(); }
@JsonView、@JsonIgnore、ObjectMapper.writerWithView()@JsonTypeInfo維護成本高、易出錯、視圖靈活性差。僅在極簡原型驗證或受限環境(無法引入第三方庫)考慮。
核心原則:視圖屬於視圖,模型屬於模型. 選擇能讓兩者獨立演進的序列化策略,才是架構師的智慧。在 Ajax 時代,JSON + 現代序列化庫已成為 90% 場景的最優解;剩餘 10% 複雜視圖定製場景,交給模板引擎專業解決。