最近專案裡前後台資料交換用上了 JSON,實際操作一輪下來有些心得,簡單整理。
JSON 全稱 JavaScript Object Notation(JavaScript 物件表示法),是一種儲存與交換文字資訊的語法,定位與 XML 類似,但更小、更快、更易解析。
和 XML 一樣,JSON 是基於純文字的資料格式。但因為它天生為 JavaScript 而生,格式設計得極為精簡:你可以用它傳輸一個字串、數字、布林值,也可以傳輸陣列或複雜的巢狀物件。這種「一套語法涵蓋所有情境」的特性,是它在 Web 開發中勝出的主因。
先看 controller 中的一段程式,重點在於資料庫查詢出來的資料如何以 JSON 格式回傳:
@RequestMapping("/work/plan/checkSubmitForApproval")
public void checkSubmitForApproval(String planId, HttpServletRequest request, HttpServletResponse response)
throws UnsupportedEncodingException {
String result = "{\"result\":\"faild\",\"personSituation\":\"null\"}";
HttpSession session = request.getSession();
String industryID = (String) session.getAttribute("industryID");
IIndustry industry = industryService.getById(industryID);
if (industry.getType().equals("XXX")) {
try {
boolean flag = false;
IProjectMain yearPlan = projectPlanService.findProjectPlanById(planId);
List<IStaffInfo> listStaffInfo = sysStaffService.getStaffByPlanId(planId, industryID);
for (int i = 0; i < listStaffInfo.size(); i++) {
if (listStaffInfo.get(i).getPractitionersPost()
.equals(StaffRole.PROGECTMANAGER.toString())) {
flag = true;
}
}
if (flag == true) {
result = "{\"result\":\"success\",\"personSituation\":\"" + yearPlan.getPerson_Situation() + "\"}";
} else {
result = "{\"result\":\"success\",\"personSituation\":\"" + yearPlan.getPerson_Situation()
+ "\",\"isManager\":\"false\"}";
}
} catch (Exception e) {
result = "{\"result\":\"falid\"}";
throw new PlatformException(e);
} finally {
OutputUtils.write(response, result, "text/x-json;charset=UTF-8");
}
}
}
這裡有個值得警惕的細節:字串拼接 JSON 是很容易出錯的做法。若 personSituation 的值中含有雙引號或反斜線,產生的 JSON 就不合法。實務上應改用 Jackson 的 ObjectMapper.writeValue() 或 Fastjson 的 JSON.toJSONString(),讓序列化庫處理跳脫。
public static void write(HttpServletResponse response, String text, String contentType) {
PrintWriter out = null;
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType(contentType);
try {
out = response.getWriter();
out.write(text);
} catch (IOException e) {
Logger.getLogger(OutputUtils.class).error(e.getMessage(), e);
} finally {
if (out != null) {
out.flush();
out.close();
}
}
}
思路很直接:關掉快取避免舊資料被快取,設定 content type 為 text/x-json;charset=UTF-8,取得 response 的 PrintWriter 後把內容寫入並收尾。
補充一點:標準的 JSON MIME type 是 application/json。text/x-json 是早期 jQuery 用來識別 JSON 回應的慣例值,如今已不建議使用。
function distribute(){
var dplanId = $(".currli").attr("id");
if (dplanId != "") {
$.ajax({
type : "POST",
url : 做驗證的 action url,
dataType : "json",
success : function(data) {
// HAVE 為已分配狀態
if (data.result == "success" && data.personSituation == "UNHAVE") {
with (document.getElementById("planForm")) {
action = 驗證合法後要提交的 url;
method = "post";
submit();
}
}
}
});
}
}
其中 success 回調函數就是驗證 action 成功後要執行的操作。宣告 dataType: "json" 時,jQuery 會自動把回應字串解析成物件,直接就能用 data.result 取值。
這是 JSON 相對 XML 最直接的優勢:jQuery 已經封裝好從 response 取資料的過程,不必再像解析 XML 那樣一層層 getElementsByTagName 讀取節點。少了這層心智負擔,開發效率的提升相當明顯。
範例中的 with 語句在嚴格模式下被禁用,且會拖慢作用域解析效能,建議改寫成 var form = document.getElementById("planForm"); form.action = ...; form.submit(); 這種直白寫法。