如何用JAVA发回JSON?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/708901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to send JSON back with JAVA?
提问by Sergio del Amo
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.
我在同时使用 Gzip 压缩和 JQuery时遇到问题。看来这可能是由我在 Struts Actions 中发送 JSON 响应的方式引起的。我使用下一个代码将我的 JSON 对象发回。
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?
有没有更好的方式在 Java Web 应用程序中发送 JSON?
采纳答案by Prabhu R
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
因为这将避免创建字符串并且 JSONObject 将直接将字节写入 Writer 对象
回答by daanish.rumani
In our project we are doing pretty much the same except that we use application/json as the content type.
在我们的项目中,除了我们使用 application/json 作为内容类型之外,我们所做的几乎相同。
Wikipedia says that the official Internet media type for JSON is application/json.
回答by StaxMan
Personally, I think using JAX-RS is the best way to deal with data binding, be that XML or JSON. Jerseyis 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.
就个人而言,我认为使用 JAX-RS 是处理数据绑定的最佳方式,无论是 XML 还是 JSON。Jersey是一个很好的 JAX-RS 实现(RestEasy 也很好),并且有很好的支持。这样你就可以使用真实的对象,不需要使用 Json.org libs 专有类。
回答by luoruofeng
response.getWriter().write(json.toString());
响应.getWriter()。写(json.toString());
change to: response.getWriter().print(json.toString());
更改为:response.getWriter()。打印(json.toString());