前後端分離架構下,JSON 是最主流的資料交換格式。本文示範 Spring MVC 後端如何序列化物件為 JSON,搭配 jQuery Ajax 非同步接收並渲染。
$.ajax({
type: "POST",
url: "apply/mystudent.action",
cache: false,
dataType: "json", // 關鍵:指定回應格式為 JSON
success: function(data) {
// data 為 JSON 陣列:[{"number":"V006","names":"LiLei"}]
$.each(data, function(index, item) {
alert("姓名:" + item.names);
alert("學號:" + item.number);
});
},
error: function(xhr, status, error) {
console.error("請求失敗:" + error);
}
});
關鍵設定: dataType: "json" 讓 jQuery 自動解析回應為 JavaScript 物件/陣列。
public String mystudent() throws Exception {
List<Student> list = priceService.query(); // 查詢資料
this.jsonUtil(list); // 序列化並輸出 JSON
return null; // 已手動輸出回應,不需視圖解析
}
public void jsonUtil(Object data) throws Exception {
HttpServletResponse response = ServletActionContext.getResponse();
String jsonStr = JsonConvert.toJson(data);
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=UTF-8");
response.getWriter().write(jsonStr);
}
import java.io.StringWriter;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonConvert {
private static final ObjectMapper mapper = new ObjectMapper();
public static String toJson(Object obj) throws Exception {
StringWriter writer = new StringWriter();
mapper.writeValue(writer, obj);
return writer.toString();
}
// 反序列化範例
public static <T> T fromJson(String json, Class<T> clazz) throws Exception {
return mapper.readValue(json, clazz);
}
}
依賴套件: 採用 Jackson (jackson-databind),現代 Java 專案標準 JSON 函式庫。
public class Student {
private String number;
private String names;
// Getter/Setter 省略
// Jackson 透過 Getter 序列化屬性名稱
}
/apply/mystudent.actionmystudent() 方法List<Student>jsonUtil() 使用 Jackson 將 List 序列化為 JSON 字串HttpServletResponse 輸出流success 回呼接收解析後的 JavaScript 陣列$.each() 迭代渲染資料| 問題 | 原因 | 解決 |
|---|---|---|
| 前端收到亂碼 | 編碼不一致 | 統一設定 UTF-8,Response 加上 charset=UTF-8 |
| 日期格式錯誤 | 預設時間戳數字 | 配置 mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")) |
| 循環參考錯誤 | 雙向關聯實體 | 使用 @JsonIgnore 或 @JsonManagedReference/@JsonBackReference |
@RestController + @ResponseBody 自動序列化spring-boot-starter-web 即內建 Jackson