问题
前端ajax请求设置返回类型为json
$.ajax({ url:path+"/getData", //请求的url地址 dataType:'json', beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("token", 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiIxNTgxMDY2NTQ3OSIsImlhdCI6MTYyODY3OTIyOH0.mhkJrDKM82BdQLf2rqlouRyZMCMGLb9HSJQhDmZRcQk'); }, contentType:"application/json;charset=utf-8", async:false,//请求是否异步,默认为异步,这也是ajax重要特性 data:encryRsa, //参数值 type:"POST", //请求方式 success:function(data){ //请求成功时处理 console.log(data); var obj = eval('(' + data+ ')'); console.log(obj); if(obj.data != null){ console.log(obj.data); } }, });
或者vue的axios请求设置返回为json
axios.post('http://127.0.0.1/api/getData', rsaStr,{ headers: { 'Content-Type': 'application/json', // 'token':'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiIxNTgxMDY2NTQ3OSIsImlhdCI6MTYyODY2NzkzNH0.U0Zc6nHakGVUZ9eHxkKO9k1MnGhk74BzC5OldZ0oVRQ' 'token':window.localStorage.getItem('token') }, responseType: 'json' }).then((res)=>{ let obj = eval('(' + res.data+ ')'); console.log(obj); }).catch(function (error) { console.log(error); });
当后台服务正常是通过注解@Responsebody
在正常情况下,从其它API 返回给前端的结果都是json字符串,前端可以正确解析
但遇到一些异常的情况,返回给前端的结果却是json对象数据,key少了双引号,前端无法正确解析
原因是
@ RestController或者@Responsebody 注解自动将对象转成了json字符串
而 response.getWriter().write() 是直接将json对象写进去,并没有自动转换成json字符串格式
private void responseResult(HttpServletResponse response, Result<?> result) { response.setCharacterEncoding("UTF-8"); response.setHeader("Content-Type", "application/json"); response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Methods", "GET, POST"); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Max-Age", "3600"); // response.setHeader("Content-type", "application/json;charset=UTF-8"); response.setStatus(HttpServletResponse.SC_OK); response.setContentType("application/json;charset=UTF-8"); // ServletOutputStream out = null; PrintWriter writer=null; try { // JSON.toJSONString(result)要获取完整的json字符串,每一个字段都要有set和get方法,不然会缺少某个字段 // response.getWriter().write(JSON.toJSONString(result)); writer=response.getWriter(); // writer.write(result.toString()); writer.write(JSON.toJSONString(result)); writer.flush(); } catch (IOException ex) { logger.error(ex.getMessage()); }finally { if(writer!=null) { writer.close(); } } }
而至于重写的toString()方法为什么没有直接返回json字符串
JSON.toJSONString(resultMap, SerializerFeature.WRITE_MAP_NULL_FEATURES) 返回的字符串中,key 是没有双引