[知了堂学习笔记]_Ajax之解析Json

请关注“知了堂学习社区”,地址:http://www.zhiliaotang.com/portal.php

1.json字符串

var str1 = '{"name":"xxx","sex":"man"}';

2.json对象

var str2 = '{"name":"xxx","sex":"man"}';

3.JavaBean转json

<button id="str02">javaBean</button>
<p id="info"></p>

$("str02").onclick = function() {
loadTextData("ajax_xml.do?method=javaBeanToJson", "GET", true, function() {
            if(xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200) {
                var res = xmlHttpReq.responseText; // 获得是一个JSON字符串

                // JSON字符串转JSON对象
                var obj = JSON.parse(res);

                // 将数据渲染到页面上
                $("info").innerText = "id : " + obj.id + " name : " + obj.name + " age : " + obj.age;
            }
        }, null);
    }

private void javaBeanToJson(HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        // TODO Auto-generated method stub
        PrintWriter out = response.getWriter();
        AjaxBean ajaxBean = new AjaxBean(1001, "zhangsan", 23);
        Gson gson = new Gson();
        String json = gson.toJson(ajaxBean); // 将JavaBean对象转成Json
        out.println(json);
        out.flush();
        out.close();
    }

4.list转json

<button id="str03">List</button>

$("str03").onclick = function() {
        loadTextData("ajax_xml.do?method=listToJson", "GET", true, function() {
            if(xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200) {
                var res = xmlHttpReq.responseText; // 获得是一个JSON字符串
                // JSON字符串转JSON对象
                var obj = JSON.parse(res);
                var info = "";
                for(i = 0; i < obj.length; i++) {
                    info += "id : " + obj[i].id + " name : " + obj[i].name + " age : " + obj[i].age + "\n\n";
                }
                $("info").innerText = info;
            }
        }, null);
    }

private void listToJson(HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        // TODO Auto-generated method stub
        response.setContentType("text/plain; charset=utf-8");
        PrintWriter out = response.getWriter();
        List<AjaxBean> list = new ArrayList<>();
        for(int i = 0; i < 3; i++) {
            AjaxBean ajaxBean = new AjaxBean(i, "zhangsan", 23);
            list.add(ajaxBean);
        }
        Gson gson = new Gson();
        String json = gson.toJson(list);
        out.println(json);
        out.flush();
        out.close();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值