版权声明:本文为博主原创文章,未经博主允许不得
示例准备工作: 1.从http://json-lib.sourceforge.net/ 下载json-lib-2.2.3-jdk15.jar。但它还依赖如下jar包: 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 如需用到json、xml之间的转换还需要 xom-1.1.jar 2.从http://www.JSON.org/json2.js下载json.js
示例一
java代码:
User user = new User("canglang");user.setName("name");JsonObject jsonUser = JsonObject.fromObject(user);reponse.getWriter().PRint(jsonUser.toString());js代码:
$.Ajax({ url : url, data : {"param1":value1, "param2":value2}, success : function(jsonData) { var jsonUser = eval(jsonData);//使用eval转换JSON字符到JSON对象 alert(jsonUser.name); }});
示例二
Java代码:
Map<User> userMap = new HashMap<User>();userMap.put("name", "canglang");userMap.put("passWord", "pwd");JsonObject jsonUserMap = JsonObject.fromObject(userMap);reponse.getWriter().print(jsonUserMap.toString());
js代码:$.ajax({ url : url, data : {"param1":value1, "param2":value2}, success : function(jsonData) { var jsonUserMap = eval(jsonData); var name = jsonUserMap.name; alert(name); }});
示例三
Java代码:
List<User> userList = new ArrayList<User>();userList.add(new User("name1", "password1"));userList.add(new User("name2", "password2"));JsonObject jsonUserList = JsonArray.fromObject(userList);
reponse.getWriter().print(jsonUserList.toString());
js代码:$.ajax({ url : url, data : {"param1":value1, "param2":value2}, success : function(jsonData) { var jsonUserList = eval(jsonData); var name = jsonUserList[0].name; alert(name); }});
示例四
js代码:
var jsonObj = {"name":"admin", "password":"password"};var text = jsonObj.toJSONString());
Java代码:JSONObject json = JSONObject.fromObject(text);User user= (User) json.toBean(jso, User.class);
可继续阅读:http://blog.csdn.net/yezi1305/article/details/4483813
新闻热点
疑难解答