Spring MVC 默認使用 Jackson 進行 JSON 序列化/反序列化。需引入核心三模塊(jackson-databind 會傳遞依賴 core 和 annotations):
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.2</version>
</dependency>
<!-- 兼容舊版代碼可選:org.codehaus.jackson:jackson-mapper-asl:1.9.13 -->
在 RequestMappingHandlerAdapter 中注入 MappingJacksonHttpMessageConverter(或 MappingJackson2HttpMessageConverter 對應 Jackson 2.x):
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
</list>
</property>
</bean>
<!-- 簡化配置:<mvc:annotation-driven /> 自動註冊 -->
@RequestBody + @ResponseBody)適用場景:前後端分離、WebService 接口、複雜巢狀對象傳輸。
// Controller
@RequestMapping("/requestJson")
public @ResponseBody ItemsCustom requestJson(@RequestBody ItemsCustom itemsCustom) {
return itemsCustom; // 直接回傳,驗證雙向轉換
}
// 前端 jQuery AJAX
$.ajax({
type: 'POST',
url: '/requestJson',
contentType: 'application/json;charset=utf-8', // 必須聲明
data: JSON.stringify({name: "手機", price: 999}), // JS對象序列化為JSON字符串
success: function(data) { console.log(data); }
});
網絡特徵:Request/Response Header 均為 Content-Type: application/json;charset=utf-8。
適用場景:傳統表單提交、簡單參數、兼容非 JSON 客戶端。
// Controller:無 @RequestBody,Spring 自動綁定請求參數到對象屬性
@RequestMapping("/responseJson")
public @ResponseBody ItemsCustom responseJson(ItemsCustom itemsCustom) {
return itemsCustom;
}
// 前端 jQuery AJAX:默認 contentType = application/x-www-form-urlencoded
$.ajax({
type: 'POST',
url: '/responseJson',
data: 'name=手機&price=999', // 字符串或對象 {name:"手機", price:999}
success: function(data) { alert(data.name); }
});
網絡特徵:Request Header Content-Type: application/x-www-form-urlencoded,Response Header application/json。
| 維度 | 請求 JSON | 請求 Key/Value |
|---|---|---|
| Controller 參數 | @RequestBody Obj | Obj(無註解) |
| 前端 Content-Type | application/json | application/x-www-form-urlencoded |
| 前端 data 格式 | JSON.stringify(obj) | obj 或 'k=v&k=v' |
| 參數綁定機制 | HTTP Message Converter 反序列化 | ServletRequestDataBinder 逐屬性綁定 |
| 支持複雜巢狀對象 | ✅ 原生支持 | ⚠️ 需自定義 PropertyEditor |
| GET 請求適用性 | ❌ 無請求體 | ✅ Query String 自然映射 |
ObjectMapper 統一 yyyy-MM-dd HH:mm:ss,避免時間戳/ISO8601 不一致。@JsonInclude(Include.NON_NULL) 減少傳輸體積。@JsonIgnore 或 @JsonBackReference。@ControllerAdvice 捕獲 HttpMessageNotReadableException 返回友好錯誤碼。