如何使用JAVA发回JSON?

我在使用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); } } } 

有没有更好的方法在Java Web应用程序中发送JSON?

代替

 try { response.getWriter().write(json.toString()); } catch (IOException e) { throw new ApplicationException("IOException in populateWithJSON", e); } 

试试这个

 try { json.write(response.getWriter()); } catch (IOException e) { throw new ApplicationException("IOException in populateWithJSON", e); } 

因为这将避免创建一个字符串,JSONObject将直接将字节写入Writer对象

在我们的项目中,除了我们使用application / json作为内容类型之外,我们几乎一样。

维基百科说, JSON的官方互联网媒体类型是application / json 。

就个人而言,我认为使用JAX-RS是处理数据绑定的最佳方式,即XML或JSON。 Jersey是一个很好的JAX-RS实现(RestEasy也很好),并且有很好的支持。 这样你可以使用真实对象,不需要使用Json.org libs专有类。

response.getWriter()。 write (json.toString());

更改为:response.getWriter()。 print (json.toString());