加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

如何用JAVA发回JSON?

发布时间:2020-12-14 05:41:42 所属栏目:Java 来源:网络整理
导读:我有问题 using Gzip compression and JQuery together.似乎这可能是由我的方式发送JSON响应在我的Struts操作.我使用下一个代码发回我的JSON对象. public ActionForward get(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletR
我有问题 using Gzip compression and JQuery together.似乎这可能是由我的方式发送JSON响应在我的Struts操作.我使用下一个代码发回我的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 Web应用程序中是否有更好的方式发送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对象

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读