我在使用Gzip压缩和JQuery时遇到问题.它似乎可能是由我在Struts Actions中发送JSON响应的方式引起的.我使用下一个代码来发送我的JSON对象.
public ActionForward get(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) {
JSONObject json = // Do some logic here
RequestUtils.populateWithJSON(response, json);
return null;
}
public static void populateWithJSON(HttpServletResponse response,JSONObject json) {
if(json!=null) {
response.setContentType("text/x-json;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
try {
response.getWriter().write(json.toString());
} catch (IOException e) {
throw new ApplicationException("IOException in populateWithJSON", e);
}
}
}
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法在Java Web应用程序中发送JSON?
Pra*_*u R 14
代替
try {
response.getWriter().write(json.toString());
} catch (IOException e) {
throw new ApplicationException("IOException in populateWithJSON", e);
}
Run Code Online (Sandbox Code Playgroud)
试试这个
try {
json.write(response.getWriter());
} catch (IOException e) {
throw new ApplicationException("IOException in populateWithJSON", e);
}
Run Code Online (Sandbox Code Playgroud)
因为这将避免创建一个字符串,JSONObject将直接将字节写入Writer对象