How to send JSON back with JAVA?

后端 未结 4 2085
你的背包
你的背包 2021-02-14 05:04

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

相关标签:
4条回答
  • 2021-02-14 05:29

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

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

    0 讨论(0)
  • 2021-02-14 05:31

    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.

    0 讨论(0)
  • 2021-02-14 05:34

    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 讨论(0)
  • 2021-02-14 05:41

    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

    0 讨论(0)
提交回复
热议问题