js之第三方工具解析JSON

1.JSON 只是一种文本字符串。它被存储在 responseText 属性中

为了读取存储在 responseText 属性中的 JSON 数据,需要根据 JavaScript 的 eval 函数。函数 eval 会把一个字符串当作它的参数。然后这个字符串会被当作 JavaScript 代码来执行。因为 JSON 的字符串就是由 JavaScript 代码构成的,所以它本身是可执行的

例如如下方式:

String json = "{username:'一叶扁舟',age:22}";
var  json = xhr.responseText;
json = eval("("+json+")");
alert(json.name);

2.利用第三方工具解析JSON

(1).需要导入的jar包


(2)代码实战:
domain实体类:

package com.wenhao.web.ajax.domain;

/**
 *类的作用:City实体类
 *
 *
 *@author 一叶扁舟
 *@version 1.0
 *@创建时间: 2014-10-28   下午05:57:18
 */

//城市[JavaBean]
public class City {
	private int id;
	private String cityName;
	public City(){}
	
	public City(int id, String cityName) {
		super();
		this.id = id;
		this.cityName = cityName;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getCityName() {
		return cityName;
	}
	public void setCityName(String cityName) {
		this.cityName = cityName;
	}

}

servlet服务处理:
package com.wenhao.web.ajax.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

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

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;

import com.wenhao.web.ajax.domain.City;

/**
 *类的作用:JavaBean直接转成JSON对象
 *这个是json传输
 *
 *
 *@author 一叶扁舟
 *@version 1.0
 *@创建时间: 2014-10-28   下午05:58:20
 */
public class CityServlet extends HttpServlet {


	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String province = request.getParameter("province");
		byte[] buf = province.getBytes("ISO8859-1");
		province = new String(buf,"UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter pw = response.getWriter();
		List<City> cityList = new ArrayList<City>();
		String jsonString = null;
		if(province.equals("河南省")){
			cityList.add(new City(1,"郑州"));
			cityList.add(new City(2,"洛阳"));
			cityList.add(new City(3,"开封"));
			cityList.add(new City(4,"信阳"));
		}else if(province.equals("福建省")){
			cityList.add(new City(1,"福州"));
			cityList.add(new City(2,"厦门"));
			cityList.add(new City(3,"莆田"));
			cityList.add(new City(4,"漳州"));
			cityList.add(new City(5,"龙岩"));
		}else if(province.equals("云南省")){
			cityList.add(new City(1,"大理"));
			cityList.add(new City(2,"昆明"));
			cityList.add(new City(3,"香格里拉"));
		}
		JsonConfig jsonConfig = new JsonConfig();
		//json数据中不包含id属性
		jsonConfig.setExcludes(new String[]{"id"});
		//将cityList转成json数组
		JSONArray jsonArray = JSONArray.fromObject(cityList,jsonConfig);
		jsonString = jsonArray.toString();
		System.out.println("jsonString="+jsonString);
		pw.write(jsonString);
		
	}

}

jsp界面获取json数据:

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
	<meta http-equiv="content-type" content="text/html; charset=UTF-8">
  </head>
  <body>
	<select id="provinceID">
		<option>选择省份</option>	
		<option>河南省</option>	
		<option>福建省</option>	
		<option>云南省</option>	
	</select>
	<select id="cityID">
		<option>选择城市</option>	
	</select>
	<script type="text/javascript">
		document.getElementById("provinceID").onchange=function(){
			//清空原city列表框
			var citySelectElement = document.getElementById("cityID");
			var cityElementArray = citySelectElement.options;
			var size = cityElementArray.length;
			if(size > 1){
			//从后向前删除下拉列表框中的东西
				for(var i=size-1;i>0;i--){
					citySelectElement.removeChild(cityElementArray[i]);
				}
			}
			var province = this[this.selectedIndex].innerHTML;
			province = encodeURI(province);
			var xhr = createXHR();
			xhr.onreadystatechange = function(){
				if(xhr.readyState==4){
					if(xhr.status==200){
						//取得json字符串
						var jsonString = xhr.responseText;
						//将json字符串转成json对象						
						var jsonObject = eval("("+jsonString+")");
						var size = jsonObject.length;
						for(var i=0;i<size;i++){
							var city = jsonObject[i].cityName;
							var optionElement = document.createElement("option");
							optionElement.innerHTML = city;
							document.getElementById("cityID").appendChild(optionElement);
						}
					}
				}
			}
			xhr.open("get","/FirstAjax/CityServlet?time="+new Date().getTime()+"&province="+province);
			xhr.send(null);
		};
		
		//创建一个ajax对象
		function createXHR(){
			var xhr = null;
			
			//如果是IE浏览器
			if(window.ActiveXObject){
				xhr = new ActiveXObject("microsoft.xmlhttp");
			}else{
		//非IE浏览器
				xhr = new XMLHttpRequest();
			}
			return xhr;
		}
	</script>
  </body>
</html>



测试效果图:


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。