json实例

关于json的原理我不再说啦,可以访问我的blog http://fuchangle.iteye.com/blog/1535377,这篇主要看看json实际的应用,下面上代码

发送数据到servlet
<%@ 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>
    <title>JSONpage</title>
<script type="text/javascript">
	var xmlHttp;
	function createXMLHttpRequest() {  
    	if (window.ActiveXObject) {  //(window.ActiveXObject)的作用,用来判断浏览器是否支持ActiveX控件,如果支持ActiveX控件,我们可以利用var xml=new ActiveXObject("Microsoft.XMLHTTP")的形式来创建XMLHTTPRequest对象
        	xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");  
     	}   
     	else if (window.XMLHttpRequest) {  //而在IE7及非IE浏览器中可以利用var xml=new XMLHttpRequest()创建XMLHttpRequest对象
        	xmlHttp = new XMLHttpRequest();  
     	}  
 	}
	
	function doJSON(){
		var car = getCarObject();
		//将js对象转化成JSON对象的text
		var carAsJSON = JSON.stringify(car);
		alert(carAsJSON);
		var url = "JSONTest1?timpStamp="+ new Date().getTime();
		createXMLHttpRequest();
		xmlHttp.open("POST",url,true);
		xmlHttp.onreadystatechange = handleStateChange;
		xmlHttp.send(carAsJSON);
	}
	
	//Ajax的回调方法
	function handleStateChange(){
		if(xmlHttp.readyState == 4){ //相应内容解析完成,可以在客户端调用啦
			if(xmlHttp.status ==200){	//交易成功
				parseResults();
			}
		}
	}
	//具体的回调动作
	function parseResults(){
		var requestDiv = document.getElementById("serverResponse");
		if(requestDiv.hasChildNodes()){
			requestDiv.removeChild(requestDiv.childNodes[0]);
		}
		//xmlHttp.responseText是servlet中返回回来的JSON格式的数据,将它创建成一个js的node对象放到DIV中
		var responseText = document.createTextNode(xmlHttp.responseText);
		requestDiv.appendChild(responseText);
		//将JSON格式的TEXT转化成JSON对象,用eval('('+response+')')
		var resultJson = eval('('+xmlHttp.responseText+')');
		alert(resultJson);
		alert(resultJson.name);
		alert(resultJson.make);
		alert(resultJson.model);
		alert(resultJson.year);
		alert(resultJson.color);
	}
	
	function Car(make,model,year,color){
		this.make = make;
		this.model = model;
		this.year = year;
		this.color = color;
	}
	
	function getCarObject(){
		return new Car("Dodge", "Coronet R/T", 1968, "yellow")	
	}
</script>
  </head>
  
  <body>
  	<form action="#">
    	<input type="button" value="Click here to send JSON data to the server" onclick="doJSON();"/>  
  	</form>
  	<h2>server response:</h2>
  	<div id="serverResponse"></div>
  </body>
</html>



servlet接受数据
package com.json.servlet;

import java.io.BufferedReader;
import java.io.IOException;

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 JSONTest1 extends HttpServlet{

	private static final long serialVersionUID = 1L;
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("----");
		String json = readJSONStringFromRequestBody(request);
		System.out.println("json = " + json);
	
		JSONObject jsonObject = JSONObject.fromObject(json);
		jsonObject.put("name", "benchi");
		System.out.println("jsonObject= " + jsonObject.toString());
		System.out.println(jsonObject.getInt("year"));
		System.out.println(jsonObject.getString("make"));
		System.out.println(jsonObject.getString("model"));
		System.out.println(jsonObject.getString("color"));
		//设置返回的格式是text
		response.setContentType("text/plain");
		response.getWriter().print(jsonObject);
	}
	
	public String readJSONStringFromRequestBody(HttpServletRequest request){
		StringBuffer json = new StringBuffer();
		String line = null;
		try {
			BufferedReader reader = request.getReader();
			while((line = reader.readLine()) != null){
				System.out.println("line= " + line);
				json.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return json.toString();
	}
}



servlet在web.xml中的配置
 <servlet>
	<servlet-name>JSONTest1</servlet-name>
	<servlet-class>com.json.servlet.JSONTest1</servlet-class>
  </servlet>
  
  <servlet-mapping>
  	<servlet-name>JSONTest1</servlet-name>
  	<url-pattern>/JSONTest1</url-pattern>
  </servlet-mapping>


至此整个工程写完啦,下面的例子也在实际中常用
package com.mengya.jsonTest;

public class JsonBean1 {
	private String col;

	private String row;

	private String value;

	public String getCol() {
		return col;
	}

	public void setCol(String col) {
		this.col = col;
	}

	public String getRow() {
		return row;
	}

	public void setRow(String row) {
		this.row = row;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}
}



package com.mengya.jsonTest;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

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

import org.apache.commons.collections.map.HashedMap;

/**
 * 
 * @author fuchangle
 * 
 */
public class JsonBanTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		boolean[] boolArray = new boolean[] { true, false, true };
		JSONArray jsonArray1 = JSONArray.fromObject(boolArray);
		System.out.println(jsonArray1);

		List list = new ArrayList();
		list.add("first");
		list.add("second");
		JSONArray jsonArray2 = JSONArray.fromObject(list);
		System.out.println(jsonArray2);

		JSONArray jsonArray3 = JSONArray.fromObject("['json','is','easy']");
		System.out.println(jsonArray3);

		Map map = new HashedMap();
		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);
		System.out.println(json);
		
		JsonBean1 jb = new JsonBean1();
		jb.setCol("col1");
		jb.setRow("row1");
		jb.setValue("123");
		JSONObject ja = JSONObject.fromObject(jb);
		System.out.println(ja.toString());
		
		List list2 = new ArrayList();
		JsonBean1 jb2 = new JsonBean1();
		jb2.setCol("col1");
		jb2.setRow("row1");
		jb2.setValue("123");
		list2.add(jb);
		list2.add(jb2);
		JSONArray jsonArray = JSONArray.fromObject(list2);
		System.out.println(jsonArray.toString());
		
		String jsonStr = "{name=\"json\",bool:true,int:1,double:2.2,func:function(a){ return a; },array:[1,2]}";
		JSONObject jsonObject = JSONObject.fromObject(jsonStr);
		System.out.println(jsonObject);
		System.out.println(jsonObject.get("name"));
		System.out.println(jsonObject.get("bool"));
		System.out.println(jsonObject.get("int"));
		System.out.println(jsonObject.get("double"));
		System.out.println(jsonObject.get("func"));
		System.out.println(jsonObject.get("array"));
		
		String basic = "{name = \"fuchangle\", age = 26, address = \"北京海淀区\"}";
		JSONObject jsonObject2 = JSONObject.fromObject(basic);
		System.out.println(jsonObject2.get("name"));
		System.out.println(jsonObject2.get("age"));
		System.out.println(jsonObject2.get("address"));
	}
	
}



你可能感兴趣的:(json)