只争朝夕 2014-08-15
读取JavaBean
1、一个JavaBean
Java代码:
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
StuBean stu = new StuBean();
stu.setId("s001");
stu.setName("Jahson");
stu.setPassword("123456");
JSONObject jsonObject = JSONObject.fromObject(stu);
out.println(jsonObject.toString());//将json放入页面
System.out.println(jsonObject);
out.flush();
out.close();
JQuery代码:
$.getJSON("servlet/MoreJson",function(data){
var str=status+"<br>";
str+="<table border=\"1\">";
str+="<tr>";
str+="<td>"+data.id+"</td>";
str+="<td>"+data.name+"</td>";
str+="<td>"+data.password+"</td>";
str+="</tr>";
str+="</table>";
$("#res").append(str);
});
2、多个JavaBean
Java代码:
response.setContentType("text/html");
PrintWriter out = response.getWriter();
StuBean stu = new StuBean();
stu.setId("s001");
stu.setName("Jahson");
stu.setPassword("123456");
StuBean stu2 = new StuBean();
stu2.setId("s002");
stu2.setName("Jack");
stu2.setPassword("654321");
List list = new ArrayList();
list.add(stu);
list.add(stu2);
JSONArray jsonArray = JSONArray.fromObject(list);
out.println(jsonArray.toString());
System.out.println(jsonArray);
out.flush();
out.close();
JQuery代码:
$.post("servlet/MoreJson",{parma:v},function(data,status){
var str="<table border=\"1\">";
$.each(data,function(index,content){
str+="<tr>";
str+="<td>"+content.id+"</td>";
str+="<td>"+content.name+"</td>";
str+="<td>"+content.password+"</td>";
str+="</tr>";
});
str+="</table>";
$("#res").append(str);
},"json");
读取List
Java代码:
response.setContentType("text/html");
PrintWriter out = response.getWriter();
List<String> list = new ArrayList<String>();
list.add("成都");
list.add("绵阳");
list.add("西昌");
list.add("aaa");
//如果是List,则必须use JSONArray instend
JSONArray jsonArray = JSONArray.fromObject(list);
out.println(jsonArray.toString());
out.flush();
out.close();
JQuery代码:
$.post("servlet/MoreJson",{parma:v},function(data,status){
var str="<table border=\"1\">";
$.each(data,function(index,content){
str+="<tr>";
str+="<td>"+content+"</td>";
str+="</tr>";
});
str+="</table>";
$("#res").append(str);
},"json");
结论:List通过each遍历数据信息;单独对象直接调用,多个对象放入LIst中通过each遍历