Spring 4 內置對 Jackson 的深度整合,配合 @ResponseBody、@RequestBody 輕鬆實現 JSON 自動序列化/反序列化。本文記錄從 JAR 依賴、前端 AJAX、Controller 配置到實體類的完整流程。
Spring 3 需手動引入 jackson-core/asl/mapper,Spring 4 僅需 jackson-databind(傳遞依賴 core/annotations):
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version> <!-- 與 Spring 4.3.x 兼容 -->
</dependency>
<!-- SpringMVC 核心 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>

<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
<script src="jquery.min.js"></script>
<script src="jquery.json-2.2.min.js"></script> <!-- 表單轉 JSON -->
<script>
// 1. 頁面加載:GET 獲取後端列表數據
$(function() {
$.ajax({
type: "GET",
contentType: "application/json",
url: "<%=request.getContextPath()%>/easyui/list.do",
dataType: "json",
success: function(data) {
if (data && data.success === "true") {
$("#info").html("共 " + data.total + " 條數據。<br/>");
$.each(data.data, function(i, item) {
$("#info").append("編號:" + item.id + ",姓名:" + item.username + ",年齡:" + item.age + "<br/>");
});
}
},
error: function() { alert("加載失敗"); }
});
});
// 2. 表單提交:POST 發送 JSON 到後端
// 表單序列化為 JSON 對象
$.fn.serializeObject = function() {
var o = {}, a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) o[this.name] = [o[this.name]];
o[this.name].push(this.value || '');
} else { o[this.name] = this.value || ''; }
});
return o;
};
$("#submit").click(function() {
var jsonStr = $.toJSON($("#form").serializeObject()); // 需 jquery.json.js
alert("發送 JSON: " + jsonStr);
$.ajax({
type: "POST",
contentType: "application/json",
url: "<%=request.getContextPath()%>/easyui/add.do",
data: jsonStr,
dataType: "json",
success: function(data) { alert("新增成功:" + data.success); },
error: function() { alert("提交失敗"); }
});
});
</script>
</head>
<body>
<div id="info"></div>
<form id="form">
編號:<input name="id" value="12"/>
姓名:<input name="username" value="走走走"/>
年齡:<input name="age" value="44"/>
<input type="button" id="submit" value="提交"/>
</form>
</body>
</html>
@Controller
@RequestMapping("/easyui")
public class JsonController {
/** GET:返回列表數據,自動序列化為 JSON */
@RequestMapping(value = "/list", method = RequestMethod.GET, consumes = "application/json")
@ResponseBody
public Map<String, Object> getUserList() {
List<UserModel> list = new ArrayList<>();
UserModel u = new UserModel();
u.setId("1"); u.setUsername("sss"); u.setAge(222);
list.add(u);
Map<String, Object> map = new HashMap<>();
map.put("total", "1");
map.put("data", list);
map.put("success", "true");
return map; // Spring 自動轉 JSON
}
/** POST:接收前端 JSON,自動反序列化為 UserModel */
@RequestMapping(value = "/add", method = RequestMethod.POST, consumes = "application/json")
@ResponseBody
public Map<String, String> addUser(@RequestBody UserModel model) {
System.out.println("接收到: " + model.getId() + " " + model.getUsername() + " " + model.getAge());
Map<String, String> map = new HashMap<>();
map.put("success", "true");
return map;
}
}
package com.zlay.pojo;
public class UserModel {
private String id;
private String username;
private int age;
// Getter/Setter 省略
}
| 註解 | 作用 | 關鍵屬性 |
|---|---|---|
| @ResponseBody | 將返回值直接寫入 HTTP Response Body,經 HttpMessageConverter 轉 JSON | 無 |
| @RequestBody | 將 HTTP Request Body 內容綁定到參數對象,經 HttpMessageConverter 解析 JSON | required=true |
| consumes="application/json" | 限制請求 Content-Type,僅處理 JSON 請求 | 值為 MIME 類型 |
| produces="application/json" | 指定響應 Content-Type(@ResponseBody 默認已設置) | 值為 MIME 類型 |
$.toJSON(obj)、$.evalJSON(str),輕量、依賴 jQueryJSON.stringify()、JSON.parse(),標準化、無依賴,推薦現代項目使用@JsonProperty、@JsonIgnore 等)jackson-databind 依賴Content-Type 不是 application/json,或 Controller 缺少 consumes 屬性@JsonProperty("keyName") 或確保駝峰命名一致ObjectMapper 設置 setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))