開發環境:spring-mvc4.1.7、fastjson1.2.7
問題描述:系統采用的前后端完全分離方式,前端頁面使用ajax調用后台服務時,想用fastjson自動轉化請求參數對象。
// 前端調用
$.ajax({ url : "bas/test.do", type : "POST", async : true, contentType : "application/json; charset=utf-8", data : country,//外層定義的json對象 success : function(rst) {alert(JSON.stringify(rst)); }
// 后台服務
1 @ResponseBody 2 @RequestMapping(value = "/add.do", method = { RequestMethod.POST, RequestMethod.GET }, produces = "application/json;charset=UTF-8") 3 public void add(@RequestBody Country country) { 4 // ... 5 }
運行報錯堆棧,如下:
嚴重: Servlet.service() for servlet [SpringMVC] in context with path [/mfd] threw exception [Request processing failed; nested exception is com.alibaba.fastjson.JSONException: syntax error, expect {, actual error, pos 0] with root cause com.alibaba.fastjson.JSONException: syntax error, expect {, actual error, pos 0 at com.alibaba.fastjson.parser.deserializer.JavaBeanDeserializer.deserialze(JavaBeanDeserializer.java:232)
網上搜索各種解決方案未果,最后嘗試將json對象轉化成json字符串,調用成功。
修改為data : JSON.stringify(country)
上一個項目使用jackson時,data參數直接傳的是json對象,fastjson不支持這種方式。。。