如何使用JAVA发回JSON? [英] How to send JSON back with JAVA?

查看:77
本文介绍了如何使用JAVA发回JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到问题一起使用Gzip压缩和JQuery 。它似乎可能是由我在Struts Actions中发送JSON响应的方式引起的。我使用下一个代码来发送我的JSON对象。

I am having problems using Gzip compression and JQuery together. It seems that it may be caused by the way I am sending JSON responses in my Struts Actions. I use the next code to send my JSON objects back.

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?

Is there a better way of sending JSON in a Java web application?

推荐答案

而不是

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对象

because this will avoid creating a string and the JSONObject will directly write the bytes to the Writer object

这篇关于如何使用JAVA发回JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆