gpt4 book ai didi

java - 如何用JAVA发回JSON?

转载 作者:搜寻专家 更新时间:2023-10-30 21:45:43 24 4
gpt4 key购买 nike

我有问题 using Gzip compression and JQuery together .看来这可能是由我在 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);
}
}
}

有没有更好的方法在 Java 网络应用程序中发送 JSON?

最佳答案

代替

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

试试这个

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

因为这会避免创建字符串,JSONObject 会直接将字节写入 Writer 对象

关于java - 如何用JAVA发回JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/708901/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com