在前後端分離架構下,JSON 已成為事實標準的資料交換格式。Spring MVC 透過 @RequestBody 與 @ResponseBody 註解,配合 Jackson 庫,實現了 HTTP 請求/回應體與 Java 物件的自動雙向轉換,徹底消除手動序列化/反序列化的樣板程式碼。
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version>
</dependency>
<mvc:annotation-driven />
前端 AJAX 請求:
$.ajax({
type: "POST",
url: "/testRequestBody",
dataType: "json",
data: { name: "韋德", age: 35 },
success: function(result) { console.log(result); }
});
後端處理:
@RequestMapping("/testRequestBody")
public String testRequestBody(@RequestParam Map<String, Object> map) {
System.out.println(map); // {name=韋德, age=35}
return "index";
}
注意:簡單平層 JSON 可直接用@RequestParam Map接收,無需@RequestBody
前端 AJAX 請求:
$.ajax({
type: "POST",
url: "/testRequestBody",
contentType: "application/json", // 關鍵:必須設定
data: JSON.stringify({ // 關鍵:必須序列化為字串
name: "韋德",
win: [2006, 2012, 2013],
age: 35
}),
success: function(result) { console.log(result); }
});
後端處理:
@RequestMapping("/testRequestBody")
public String testRequestBody(@RequestBody Map<String, Object> map) {
System.out.println(map); // {name=韋德, win=[2006, 2012, 2013], age=35}
return "index";
}
| 條件 | 說明 |
|---|---|
| Content-Type | 必須為 application/json |
| 資料格式 | 必須為 JSON 字串 (使用 JSON.stringify()) |
| 參數類型 | Map、自定義 POJO、List 等 |
private void writeJson(HttpServletResponse response, Object object) {
String json = JSON.toJSONString(object); // 需額外引入 fastjson/jackson
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
try (PrintWriter out = response.getWriter()) {
out.write(json);
} catch (IOException e) {
e.printStackTrace();
}
}
前端調用:
$.ajax({
type: "POST",
url: "/testResponseBody",
dataType: "json",
success: function(result) { console.info(result); }
});
後端處理:
@RequestMapping("/testResponseBody")
@ResponseBody
public Map<String, Object> testResponseBody() {
Map<String, Object> result = new HashMap<>();
result.put("name", "韋德");
result.put("age", 35);
return result; // 自動轉為 JSON: {"age":35,"name":"韋德"}
}
public class User {
private String name;
private int age;
private List<String> hobbies;
// getter/setter 省略
}
@PostMapping("/user")
@ResponseBody
public User createUser(@RequestBody User user) {
// 直接獲得完整物件,自動驗證可加 @Valid
userService.save(user);
return user; // 自動序列化回傳
}

| 問題 | 原因 | 解決 |
|---|---|---|
| 400 Bad Request | Content-Type 錯誤或 JSON 格式不合法 | 檢查前端 contentType 與 JSON.stringify() |
| 字段為 null | JSON key 與 Java 屬性名不匹配 | 使用 @JsonProperty 或確保駝峰命名一致 |
| 日期格式錯誤 | 預設時間戳格式 | 配置 ObjectMapper 日期格式 |
| 循環引用錯誤 | 雙向關聯實體序列化 | 使用 @JsonIgnore 或 @JsonBackReference |
@Valid @RequestBody UserDTO dto 配合 JSR-303 註解@ControllerAdvice 捕獲 HttpMessageNotReadableException 回傳友善錯誤掌握 @RequestBody 與 @ResponseBody 是 Spring MVC 開發的核心技能,配合 Jackson 強大的序列化能力,能讓你專注於業務邏輯而非資料轉換細節,大幅提升開發效率與程式碼品質。