How to send JSON back in Java?

I have a problem using gzip compression and jQuery together It seems that this may be the way I send JSON responses in my struts operations I use the next code to send back my JSON object

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);
        }                               
    }
 }

Is there a better way to send JSON in Java Web applications?

Solution

replace

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

Try this

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

This avoids creating a string, and jsonobject writes bytes directly to the writer object

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>