日期:2014-05-16  浏览次数:20423 次

Json字符串和Json对象的相互转换以及Json的访问
<%@ 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 'jsonConvert.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">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
<script type="text/javascript" src="js/json2.js"></script>
	<script>
	//Json对象转换成字符串
	function convertJsontoString(){
		var myJsonObj=[{"name":"name1","age": "age1","sex" : "sex1"},{"name":"name2","age": "age2","sex" : "sex2"}];
		var myJSONText = JSON.stringify(myJsonObj);
		alert(myJSONText);
		document.write(myJSONText);
	}
	//convertJsontoString();

	  //Json格式字符串转换成Json对象
	function convertStringToJson(){
		alert("字符串转成Json");
		var jsonString='[{"name":"name1","age":"age1","sex":"sex1"},{"name":"name2","age":"age2","sex":"sex2"}]';
		var 	myData = JSON.parse(jsonString, function (key, value) {
            return key.indexOf('date') >= 0 ? new Date(value) : value;
        });
        //Json对象的访问。
		alert(myData[0].name);
		alert(myData[0].age);
		alert("字符串转成Json完毕.");
		}
	convertStringToJson();

	function visitJson(){

		var json = '{"a":"1", "b":"2"}';
		var data = eval('('+ json +')');
		alert(data.a);
		alert(data['a']);
		}
	visitJson();
	
	</script>
  </head>
  
  <body>
  </body>
</html>

?