自己对前台解析Json、后台生成Json的理解和测试

来源:互联网 发布:数位板绘画软件 编辑:程序博客网 时间:2024/04/30 23:41

这次练习只用到了前台JSP页面和后台Controller里方法,不走数据库。在controller里模拟数据库。

首先建了一个student实体类。然后在controller里创建3个对象。

 student sd1 = new student(1,"bob",23); student sd2 = new student(2,"tom",25); student sd3 = new student(3,"jax",27);

然后创建JSONArray对象,直接将实体对象放进去。

 JSONArray json = new JSONArray();        json.add(sd1);        json.add(sd2);        json.add(sd3);

或者创建JSONOjbject对象,也可以;

JSONObject json = new JSONObject();        json.put("s1",sd1);        json.put("s2",sd2);        json.put("s3",sd3);

要么就是像Mybatis一样,直接返回个list集合,然后将集合装进JSONArray里,这种貌似最经典,常用。注意静态方法!!!

List<student> list = new ArrayList<student>();        list.add(sd1);
list.add(sd2);
        list.add(sd3);
JSONArray json = JSONArray.fromObject(list);


还有邪教专用的就是将map集合,放进JSONObject里,

Map<String,student> map =new HashMap<String,student>();        map.put("sd1",sd1);        map.put("sd2",sd2);        map.put("sd3",sd3);JSONObject json = JSONObject.fromObject(map)

基本上就这些方式,下面就是创建流来响应到前台。

PrintWriter pw = null;        try {            pw = response.getWriter();            pw.write(json.toString());        }catch (IOException e){            e.printStackTrace();        }finally{            if(pw != null){                pw.close();            }        }

好了,controller里就完事了。下面就是JSP里处理JSON了。


首先是ajax部分

 $(function(){        $.ajax({              url: "/json1.action",              dataType : "json",              type : "post",              success : function(result,status,xhr){                  console.log(result);                  console.log(status);                  console.log(xhr);                 /* console.log(result[0].sname);*/                  /*var data = JSON.parse(result);*/                   /* var data = eval('('+result+')');*/                  addhtml(result);              },              error : function(xhr,status,error){                alert("ajax异常");                console.log(error);                console.log(status)                console.log(xhr);              }          });      });

然后调用addhtml()方法。

 function addhtml(data){        var t_body = "";        /*遍历json数组*/        /*for(var i = 0;i<data.length;i++){            t_body += "<tr><td>"+data[i].sid+"</td>"+"<td>"+data[i].sname+"</td>"+"<td>"+data[i].sage+"</td></tr>";        }*/        /*遍历json对象*/        for(var i in data){          t_body += "<tr><td>"+data[i].sid+"</td>"+"<td>"+data[i].sname+"</td>"+"<td>"+data[i].sage+"</td></tr>";        }        $("tbody").html(t_body);      }

上边有两种遍历方式,第一种偏向与后台是JSONArray的json,for( var i in data)这种没有任何限制,也不出错。用html拼接来加入到tbody里。

<table border="1">    <thead>        <td>编号</td>        <td>姓名</td>        <td>年龄</td>    </thead>    <tbody></tbody>  </table>

基本上就是这样。

页面就是



好了,折腾到最后,才知道,json有两种,一种是对象,一种就是字符串。 上面进行解析的只能是json对象。如果不是对象,用JSON.parse().来转换。










阅读全文
0 0
原创粉丝点击