1.首先下载json所以依赖的包, Json-lib 最新版 json-lib-2.3-jdk15.jar,其官方网站是:http://json-lib.sourceforge.net/可以直接download,细心的你会发现其网站页面里面有提示它还需要其他包:
Json-lib requires (at least) the following dependencies in your classpath:
•jakarta commons-lang 2.4
•jakarta commons-beanutils 1.7.0
•jakarta commons-collections 3.2
•jakarta commons-logging 1.1.1
•ezmorph 1.0.6
下载地址分别是:
http://commons.apache.org/lang/
http://commons.apache.org/beanutils/
http://commons.apache.org/collections/
http://commons.apache.org/logging/
http://ezmorph.sourceforge.net/
2.首先先见一个小web项目
User类:
packagecom.json;public classUser {
String username;
String password;publicString getUsername() {returnusername;
}public voidsetUsername(String username) {this.username =username;
}publicString getPassword() {returnpassword;
}public voidsetPassword(String password) {this.password =password;
}
}
servlet :
packagecom.json;importjava.io.IOException;importjava.io.PrintWriter;importjava.util.ArrayList;importjava.util.List;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importnet.sf.json.JSONArray;public class TestJson extendsHttpServlet {public voiddoGet(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {
doPost(request,response);
}public voiddoPost(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {
response.setContentType("text/html");
String str= =request.getParameter("name");//得到ajax传递过来的paramater
PrintWriter out=response.getWriter();
List list= new ArrayList();//传递List
Map m=new HashMap();//传递Map
User u1=newUser();
u1.setUsername("zah");
u1.setPassword("123");
User u2=newUser();
u2.setUsername("ztf");
u2.setPassword("456");
list.add(u1);//添加User对象
list.add(u2); //添加User对象
m.put("u1", u1);
m.put("u2", u2);
JSONArray jsonArray2=JSONArray.fromObject( list );//把java数组转化成转化成json对象
JSONObject jo=JSONObject.fromObject(m);//转化Map对象
out.print(jsonArray2);//返给ajax请求
out.print(jo);//返给ajax请求
}
}
ajax实现:
functiontest(){
$.ajax({
type:"POST",//请求方式
url:"testjson",//请求路径
cache:false,
data:"name=zah",//传参
dataType:'json',//返回值类型
success:function(json){
alert(json[0].username+" "json[0].password);//弹出返回过来的List对象
}
});
}
输出:zah 123
访问Map的话直接把返回函数改成如下即可:
success:function(json){
alert(json.u1.username)
}