问题描述
用struts2的json插件,直接action 生成 json数据 ,生成的数据是 {"jsona":[{"total":"a","total2":"a2"}]}我前台显示用的是easyui,数据格式是[{"total":"a","total2":"a2"}],如何能直接action生成这种数据格式呢?最好不通过jsp页面转
解决方案
你用jquery回调的时候应该是把数组转换成json了吧.在后台转换吧。可以用这种方式。public ActionForward queryJsonString(ActionMapping mapping,ActionForm form, HttpServletRequest request,HttpServletResponse response) throws Exception {logger.debug("json输出演示");List<Tblorder> list = tblorderdao.queryAllTblorder();response.setContentType("text/plain;charset="+ request.getCharacterEncoding());PrintWriter pw = response.getWriter();StringBuilder sb = new StringBuilder();sb.append("{"list":[");for (Tblorder tblorder : list) {sb.append(String.format("{"orderid":%s,"info":"%s","customer":"%s"},",tblorder.getOrderid(), tblorder.getInfo(), tblorder.getCustomer()));}if (!list.isEmpty()) {sb.deleteCharAt(sb.length() - 1);}sb.append("]}");pw.print(sb.toString());return null;}
解决方案二:
方法太多1:拼字符串2:用google的gson生成json数据。。。至于你action会生成{"jsona":[{"total":"a","total2":"a2"}]} 是因为你首先生成了一个object,object中又生成array,所以是这样的格式,你要生成array就和前台格式一样了
解决方案三:
后台封装成String类型数据如:"{'total':'a','total2':'a2'}" 前台接收即可,不行的话在eval('('+data+')')一下