当前位置: 代码迷 >> JavaScript >> json施用
  详细解决方案

json施用

热度:336   发布时间:2012-09-25 09:55:58.0
json使用

?

?JavaScript?中使用?JSON

掌握了?JSON?格式之后,在?JavaScript?中使用它就很简单了。JSON??JavaScript?原生格式,这意味着在?JavaScript?中处理?JSON?数据不需要任何特殊的?API?或工具包。

?JSON?数据赋值给变量

例如,可以创建一个新的?JavaScript?变量,然后将?JSON?格式的数据字符串直接赋值给它:

var people =
?{ "programmers": [
??? { "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" },
??? { "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" },
??? { "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" }
?? ],
?"authors": [
??? { "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
??? { "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
??? { "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }
?? ],
?"musicians": [
??? { "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
??? { "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }
?? ]
?}

?

这非常简单;现在?people?包含前面看到的?JSON?格式的数据。但是,这还不够,因为访问数据的方式似乎还不明显。

访问数据

尽管看起来不明显,但是上面的长字符串实际上只是一个数组;将这个数组放进?JavaScript?变量之后,就可以很轻松地访问它。实际上,只需用点号表示法来表示数组元素。所以,要想访问?programmers?列表的第一个条目的姓氏,只需在?JavaScript?中使用下面这样的代码:

people.programmers[0].lastName;

?

注意,数组索引是从零开始的。所以,这行代码首先访问?people?变量中的数据;然后移动到称为?programmers?的条目,再移动到第一个记录([0]);最后,访问?lastName?键的值。结果是字符串值?McLaughlin”。

下面是使用同一变量的几个示例。

people.authors[1].genre?????????????????????? // Value is "fantasy"
?
people.musicians[3].lastName????????? // Undefined. This refers to the fourth entry,
 and there isn't one
?
people.programmers.[2].firstName????? // Value is "Elliotte"

?

利用这样的语法,可以处理任何?JSON?格式的数据,而不需要使用任何额外的?JavaScript?工具包或?API

修改?JSON?数据

正如可以用点号和括号访问数据,也可以按照同样的方式轻松地修改数据:

people.musicians[1].lastName = "Rachmaninov";

?

在将字符串转换为?JavaScript?对象之后,就可以像这样修改变量中的数据。

转换回字符串

当然,如果不能轻松地将对象转换回本文提到的文本格式,那么所有数据修改都没有太大的价值。在?JavaScript?中这种转换也很简单:

String newJSONtext = people.toJSONString();

?

这样就行了!现在就获得了一个可以在任何地方使用的文本字符串,例如,可以将它用作?Ajax?应用程序中的请求字符串。

更重要的是,可以将任何?JavaScript?对象转换为?JSON?文本。并非只能处理原来用?JSON?字符串赋值的变量。为了对名为?myObject?的对象进行转换,只需执行相同形式的命令:

String myObjectInJSON = myObject.toJSONString();

?

eval()可以直接读取json的字符串

?

package com.nanjing.json;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 * json测试
 * 
 * @author alyssa
 *lib:commons-lang.jar commons-beanutills.jar commons-collections.jar
 * commons-logging.jar json.jar ezmorph.jar
 */
public class JsonlibTest{
	private static	Logger logger=Logger.getLogger(JsonlibTest.class); 
	private static	JSONArray jsonArray = null;
	private static	JSONObject jsonObject = null;
	private static	Student student = null;

	@BeforeClass
	public static void initClass(){
		logger.info("test init....");
		jsonArray = new JSONArray();
		jsonObject = new JSONObject();
		student = new Student(123,false,new char[]{'a','b','c'},"function(i){ return this.options[i]; }");		
	}
	
	@AfterClass
	public static void distoryClass(){
		 logger.info("test distory....");
		 jsonArray = null;
		 jsonObject = null;
		 student = null;
	}
	
	@Before
	public void init(){
	}

	@After
	public void distory(){
	}

	
	@SuppressWarnings("unchecked")
	@Test(timeout=1200)
	public void testArray(){
		//布尔值数组
		boolean[] boolArray={true,false,false};
		jsonArray=JSONArray.fromObject(boolArray);
		logger.info(jsonArray);
		
		//from collection to JSON
		List mylist=new ArrayList();
		mylist.add("name");
		mylist.add("alyssa");
		jsonArray=JSONArray.fromObject(mylist);
		logger.info(jsonArray);
		
		//from map to JSON
		Map map=new HashMap();
		map.put("name", "alyssa");
		map.put("password", "19871102");
		map.put("isMarry", false);
		jsonObject=JSONObject.fromObject(map);
		logger.info(jsonObject);
		
		//from bean to JSON
		jsonObject=JSONObject.fromObject(student);
		logger.info(jsonObject);
		
		//from JSON to Dynabean
		Object object=JSONObject.toBean(jsonObject);
		try {
			logger.info(jsonObject.get("name"));
			Assert.assertEquals(jsonObject.get("name"),PropertyUtils.getProperty(object, "name"));
		} catch (IllegalAccessException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		} catch (InvocationTargetException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		
		//from JSON to bean
		jsonObject=JSONObject.fromObject(student);
		Student student=(Student)JSONObject.toBean(jsonObject,Student.class);
		logger.info(student.isName());
		//Assert.assertEquals(jsonObject.get("name"), Boolean.valueOf(student.isName()));
	}
}
?

? 实体类

?package com.nanjing.json;

import java.util.Arrays;

public class Student {
	private int id;
	private boolean name;
	private char[] options;
	private String func1;
	
	public Student(int id, boolean name, char[] options, String func1) {
		this.id = id;
		this.name = name;
		this.options = options;
		this.func1 = func1;
	}
	
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public boolean isName() {
		return name;
	}

	public void setName(boolean name) {
		this.name = name;
	}

	public char[] getOptions() {
		return options;
	}

	public void setOptions(char[] options) {
		this.options = options;
	}

	public String getFunc1() {
		return func1;
	}

	public void setFunc1(String func1) {
		this.func1 = func1;
	}

	@Override
	public String toString() {
		return "Student [func1=" + func1 + ", id=" + id + ", name=" + name
				+ ", options=" + Arrays.toString(options) + "]";
	}
	
}
?

结合servlet使用

?

?

package com.nanjing.json;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

public class TestJSONServlet extends HttpServlet{

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		PrintWriter out=response.getWriter();
		Student stu=new Student(12,true,new char[]{'a','b'},"hehe");
		JSONObject jSONObject=JSONObject.fromObject(stu);
		out.write(jSONObject.toString());
		out.flush();
	}

}

?jsp页面

?

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.4.2.min.js"></script>
<title>Insert title here</title>
<script type="text/javascript">
	$(function(){
		$.post("testJSONServlet",function(date){
			alert(date.id);
			alert(date.name);
		},"json");
	});

</script>
</head>
<body>
	
</body>
</html>

?

web.xml

?

  <servlet>
  	<servlet-name>testJSON</servlet-name>
  	<servlet-class>com.nanjing.json.TestJSONServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
  	<servlet-name>testJSON</servlet-name>
  	<url-pattern>/testJSONServlet</url-pattern>
  </servlet-mapping>
?

?

  相关解决方案