一、JAR包简介
要使程序可以运行必须引入JSON-lib包,JSON-lib包同时依赖于以下的JAR包:
1.commons-lang.jar
2.commons-beanutils.jar
3.commons-collections.jar
4.commons-logging.jar
5.ezmorph.jar
6.json-lib-2.2.2-jdk15.jar
二、后台处理
1.JSONObject用于处理单个对象
User user = new User("zhangsan",200);
JSONObject json = JSONObject.fromObject(user);
System.out.println("=========="+json+"==========");
PrintWriter out = response.getWriter();
out.print(json);
out.flush();
out.close();
返回的结果:=========={"name":"zhangsan","money":200}==========
2.JSONArray用于处理集合例如list
User user1 = new User("zhangsan",200);
User user2 = new User("lisi",400);
List<User> userList = new ArrayList<User>();
userList.add(user1);
userList.add(user2);
JSONArray jsonArray = JSONArray.fromObject(userList);
System.out.println("==========jsonArray: "+jsonArray+" ==========");
PrintWriter out = response.getWriter();
out.print(jsonArray);
out.flush();
out.close();
返回的结果:==========jsonArray: [{"name":"zhangsan","money":200},{"name":"lisi","money":400}] ==========
三、前台js处理
1.JSONObject返回的单个对象
$(document).ready(function(){
var url = "<%=basePath%>servlet/jsonServlet";
$.get(url,{
},function(data){
$('#onLine_count').text(data.money);
},"json");
});
2.JSONArray返回的数组
$.getJSON(url,{"parentGroupId":parentGroupId}, function(json){
$('#first_sort_org').empty();
for(var i=0;i<json.length;i++) {
var code = json[i].id;
var name = json[i].name;
if(type=="groupUser") {
name = json[i].showName;
}
var childSelectId = 'first_sort_org';
$("<option></option>").val(code).text(i+1+". "+name).appendTo($('#first_sort_org'));
}
});
posted on 2011-05-02 21:25
RoyPayne 阅读(1718)
评论(0) 编辑 收藏 所属分类:
json