11

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

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

1
  • 1
    I used response.setContentType("application/json;charset=UTF-8"); instead of response.setContentType("text/x-json;charset=UTF-8");
    – bentzy
    Apr 6, 2014 at 11:33

4 Answers 4

15

Instead of

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

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

1
  • I'm working on something similar, which library is used to import json.write()?
    – codeBarer
    Mar 17, 2014 at 18:16
5

In our project we are doing pretty much the same except that we use application/json as the content type.

Wikipedia says that the official Internet media type for JSON is application/json.

1

Personally, I think using JAX-RS is the best way to deal with data binding, be that XML or JSON. Jersey is a good JAX-RS implementation (RestEasy is good too), and has good support. That way you can use real objects, no need to use Json.org libs proprietary classes.

0

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

change to: response.getWriter().print(json.toString());

1
  • uhm, just to write something? Jun 30, 2016 at 10:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.