Jquery JSON操作应用

今天闲暇时间没事,看到群里有人询问json数据操作,然后回顾一下,做一个笔记吧!
使用JSON需要的包有:
commons-beanutils-1.7.0.jar 
commons-lang-2.1.jar
ezmorph-1.0.2.jar
json-lib-1.1-jdk15.jar

在后台把数据封装成json数据格式传到前台
1. List集合转换成json代码
List list = new ArrayList();
list.add( "first" );
list.add( "second" );
JSONArray jsonArray2 = JSONArray.fromObject( list );
2. Map集合转换成json代码
Map map = new HashMap();
map.put("name", "json");
map.put("bool", Boolean.TRUE);
map.put("int", new Integer(1));
map.put("arr", new String[] { "a", "b" });
map.put("func", "function(i){ return this.arr[i]; }");
JSONObject json = JSONObject.fromObject(map);
3. Bean转换成json代码
JSONObject jsonObject = JSONObject.fromObject(new JsonBean());
4. 数组转换成json代码
boolean[] boolArray = new boolean[] { true, false, true };
JSONArray jsonArray1 = JSONArray.fromObject(boolArray);
5. 一般数据转换成json代码
JSONArray jsonArray3 = JSONArray.fromObject("['json','is','easy']" );


[color=red]response.getWriter().write(jsonArray2.toString());[/color]

前台页面的解析:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'json.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
	<script type="text/javascript">
		$(document).ready(function(){
		var txt = '{"employees":[' +
			'{"firstName":"Bill","lastName":"Gates" },' +
			'{"firstName":"George","lastName":"Bush" },' +
			'{"firstName":"Thomas","lastName":"Carter" }]}';
			
		var JSONObject= {
				"name":"Bill Gates",
				"street":"Fifth Avenue New York 666",
				"age":56,
				"phone":"555 1234567"};
		var book = '{"hcz":[{"author":"hong","author1":"honglou"},{"author":"hong1","author1":"honglou1"}]}';
			$("#btn").click(function(){
				var dataObject = eval("("+txt+")");
				alert(dataObject.employees[1].firstName);
			});
			$("#btn1").click(function(){
				alert(JSONObject.name);
			});
			$("#btn2").click(function(){
				var bookObject = eval("("+book+")");
				alert(bookObject.hcz[1].author);
			});
			
		});
	</script>
	
  </head>
  
  <body>
   <input type="button" value="Button0" id="btn" />
   <input type="button" value="Button1" id="btn1" />
    <input type="button" value="Button2" id="btn2" />
  </body>
</html>

猜你喜欢

转载自hechuanzhen.iteye.com/blog/1634297
今日推荐