Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send JSON back with JAVA?

Tags:

java

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

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

like image 978
Sergio del Amo Avatar asked Apr 02 '09 09:04

Sergio del Amo


2 Answers

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

like image 77
Prabhu R Avatar answered Oct 05 '22 11:10

Prabhu R


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.

like image 44
daanish.rumani Avatar answered Oct 05 '22 13:10

daanish.rumani