`
hanwesley
  • 浏览: 57317 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

JSON web应用前后端通讯的轻量级结果处理

 
阅读更多

JSON是一种传递对象的语法,对象可以是name/value对,数组和其他对象。

Json格式相对XML一种轻量级的返回结果。

如何将Java对象封装为Json格式,以下是一个Demo。

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

class Test{
    public static void main(String [] args){
        JSONObject obj = new JSONObject();
        GroupKeeperJSON do1 = new GroupKeeperJSON();
        do1.setqID("111");
        GroupKeeperJSON do2 = new GroupKeeperJSON();
        do2.setqName("name");
        JSONArray array = new JSONArray();
        array.add(do1);
        array.add(do2);
        obj.put("list", array);
        Message msg = new Message(false);
        msg.setMessage("OKK");
        obj.put("info", msg);
        System.out.println(obj);
    }
}


当输出到页面时默认是text/html格式,对contextType需要修改为text/xml,如果需要进行编码,也需要对charset进行修改。

具体方法:

HttpServletResponse response = runData.getResponse();
response.setContentType("text/xml;charset=UTF-8");
response.getWrite().write(jsonStr);

前段页面处理

function joinAction(cID,qID,qName,type){
        YUI().use('node','dialog','io',function(Y){
            Y.io('${keeperModule}/market/cps_group_service.do',{
            on: {
                success: function(id,o){
                    eval("var s = " + o.responseText);//处理JSON返回结果
                    alert(s.msg);
                }
            },
            method: "GET",
            data: "cid="+cID+"&qid="+qID+"&act="+type+"&time=" + new Date().getTime()//加时间戳是为了防止多次打开无效
            });
    dialog_joinGroup.close();
    });
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics