服务器端的工作就是将特定的数据类型转换为json字符串,然后客户端再将json字符串转换成原来的类型,所以json解析是跨平台数据格式转换的一个桥梁,

这里以最常用的对象类型,list包裹对象类型,list包裹String类型,以及list包裹Map对象类型4种情况为例简单介绍json的数据解析

服务器端json所用到的jar包下载(免积分)  服务器端源码下载(免积分)

一、首先服务器端将数据转换为json格式

  1. 首先建立一个Person对象类,后面就是将person对象转换为json格式
package com.zml.pojo;

/**
 * @author zml2015
 * @Time:2016年2月2日 下午10:35:05
 * @version 1.0
 */
public class Person {

	String name;
	String sex;
	String QQ;
	String contact;

	public Person() {
		// TODO Auto-generated constructor stub
	}

	public Person(String name, String sex, String qQ, String contact) {
		super();
		this.name = name;
		this.sex = sex;
		QQ = qQ;
		this.contact = contact;
	}

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name
	 *            the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return the sex
	 */
	public String getSex() {
		return sex;
	}

	/**
	 * @param sex
	 *            the sex to set
	 */
	public void setSex(String sex) {
		this.sex = sex;
	}

	/**
	 * @return the qQ
	 */
	public String getQQ() {
		return QQ;
	}

	/**
	 * @param qQ
	 *            the qQ to set
	 */
	public void setQQ(String qQ) {
		QQ = qQ;
	}

	/**
	 * @return the contact
	 */
	public String getContact() {
		return contact;
	}

	/**
	 * @param contact
	 *            the contact to set
	 */
	public void setContact(String contact) {
		this.contact = contact;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "Person [name=" + name + ", sex=" + sex + ", QQ=" + QQ
				+ ", contact=" + contact + "]";
	}

}
  1. 我写了一个工具类,用来生成上述的四种类型的数据;
package com.zml.utils;

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

import com.zml.pojo.Person;

/**
 * 用于生成四种类型的数据来测试json解析:
 * ①Person对象类型 ②List<Person> ③List<String> ④List<Map<String,Object>>
 * 
 * @author zml2015
 * @Time:2016年2月2日 下午10:38:40
 * @version 1.0
 */
public class DataUtil {

	public static Person getPerson() {

		return new Person("zml2015", "男", "1072307340", "157*****573");
	}

	public static List<Person> getPersons() {
		List<Person> list = new ArrayList<Person>();
		list.add(getPerson());
		list.add(new Person("张三", "男", "123456789", "98765432"));
		list.add(new Person("李四", "女", "762348234", "12312124324"));
		return list;

	}
	
	public static List<String>	getStrings(){
		List<String>list = new ArrayList<String>();
		list.add("zml2015");
		list.add("张三");
		list.add("李四");
		
		return list;
	}
	
	public static List<Map<String,Object>> getMaps(){
		
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("name","zml2015" );
		map.put("blog", "blog.csdn.net/zml_2015");
		map.put("person", getPerson());
		list.add(map);
		return list;
		
	}

}

  1. 接下来就是写json数据类型的转换类了
package com.zml.utils;

import net.sf.json.JSONObject;

/**
 * @author zml2015
 * @Time:2016年2月2日 上午12:18:38
 * @version 1.0
 */
public class JsonTools {
	
	
	public static String  createJsonString(String key,Object value){
		
		JSONObject jsonObject=new JSONObject();
		jsonObject.put(key, value);
		return jsonObject.toString();
		
		}
	
}
  1. 进行测试,看是否将上述4种数据转换为了json的数据类型
package com.zml.test;

import com.zml.utils.DataUtil;
import com.zml.utils.JsonTools;

/**
 * @author zml2015
 * @Time:2016年2月2日 上午12:27:29
 * @version 1.0
 */
public class testjson {

	public static void main(String[] args) {
			String jsonString;
			jsonString = JsonTools.createJsonString("person",DataUtil.getPerson());

			System.out.println(jsonString);			
			jsonString = JsonTools.createJsonString("persons",DataUtil.getPersons());

			System.out.println(jsonString);			
			jsonString = JsonTools.createJsonString("strings",DataUtil.getStrings());

			System.out.println(jsonString);		
			jsonString = JsonTools.createJsonString("maps",DataUtil.getMaps());
			System.out.println(jsonString);		
		}
		
	

}

image.png

  1. 测试成功后,建立Servlet类,以方便将json数据传输给客户端
package com.zml.test;

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 com.zml.utils.DataUtil;  
import com.zml.utils.JsonTools;

/** 
 * @author zml2015 
 * @Time:2016年2月2日 下午10:54:26 
 * @version 1.0 
 */  
public class JsonServlet extends HttpServlet {

/** 
  * Constructor of the object. 
  */  
 public JsonServlet() {  
  super();  
 }

/** 
  * Destruction of the servlet.  
  */  
 public void destroy() {  
  super.destroy(); // Just puts "destroy" string in log  
  // Put your code here  
 }

/** 
  * The doGet method of the servlet.  
  *  
  * This method is called when a form has its tag value method equals to get. 
  *  
  * @param request 
  *            the request send by the client to the server 
  * @param response 
  *            the response send by the server to the client 
  * @throws ServletException 
  *             if an error occurred 
  * @throws IOException 
  *             if an error occurred 
  */  
 public void doGet(HttpServletRequest request, HttpServletResponse response)  
   throws ServletException, IOException {  
  this.doPost(request, response);

}

/** 
  * The doPost method of the servlet.  
  *  
  * This method is called when a form has its tag value method equals to 
  * post. 
  *  
  * @param request 
  *            the request send by the client to the server 
  * @param response 
  *            the response send by the server to the client 
  * @throws ServletException 
  *             if an error occurred 
  * @throws IOException 
  *             if an error occurred 
  */  
 public void doPost(HttpServletRequest request, HttpServletResponse response)  
   throws ServletException, IOException {

 response.setContentType("text/html;charset=utf-8");  
  request.setCharacterEncoding("utf-8");  
  response.setCharacterEncoding("utf-8");  
  PrintWriter out = response.getWriter();

 String jsonString="";  
  String  actionString = request.getParameter("action");  
    
  if (actionString.equals("person")) {  
     
   jsonString = JsonTools.createJsonString("person",DataUtil.getPerson());

 } else if (actionString.equals("persons")) {  
     
   jsonString = JsonTools.createJsonString("persons",DataUtil.getPersons());

 } else if (actionString.equals("strings")) {  
     
   jsonString = JsonTools.createJsonString("strings",DataUtil.getStrings());

 } else if (actionString.equals("maps")) {  
     
   jsonString = JsonTools.createJsonString("maps",DataUtil.getMaps());  
     
  }  
    
  out.write(jsonString);

}

/** 
  * Initialization of the servlet.  
  *  
  * @throws ServletException 
  *             if an error occurs 
  */  
 public void init() throws ServletException {  
  // Put your code here  
 }

}  

通过网址访问可得到的JSON数据:
2021/01/20/792500120105004.png
2021/01/20/a2f4a0120105020.png
2021/01/20/be7490120105041.png
2021/01/20/398180120105104.png

二、客户端解析json数据

这里暂时只贴出重要的解析部分

package com.zml.util;

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

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.zml.pojo.Person;

/**
 * 解析数据:将json字符串解析还原成原来的数据类型
 * 
 * @author zml2015
 * @date 2016-2-3 上午12:11:57
 * @version 1.0
 */
public class JsonTools {

	public static Person getPerson(String key, String jsonString) {
		Person person = new Person();
		// 将json字符串转换成json对象
		try {
			JSONObject jsonObject = new JSONObject(jsonString);
			// 将json对象根据key(person),拿到对应的value(Person对象)值
			JSONObject jsonObject2 = jsonObject.getJSONObject(key);
			// 将拿到的对象set到一个person对象中
			person.setName(jsonObject2.getString("name"));
			person.setSex(jsonObject2.getString("sex"));
			person.setQQ(jsonObject2.getString("QQ"));
			person.setContact(jsonObject2.getString("contact"));
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return person;

	}

	public static List<Person> getPersons(String key, String jsonString) {
		List<Person> list = new ArrayList<Person>();
		JSONObject jsonObject;
		try {
			jsonObject = new JSONObject(jsonString);
			JSONArray Persons = jsonObject.getJSONArray(key);
			for (int i = 0; i < Persons.length(); i++) {
				Person person = new Person();
				JSONObject jsonObject2 = Persons.getJSONObject(i);
				person.setName(jsonObject2.getString("name"));
				person.setSex(jsonObject2.getString("sex"));
				person.setQQ(jsonObject2.getString("QQ"));
				person.setContact(jsonObject2.getString("contact"));

				list.add(person);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return list;
	}

	public static List<String> getStrings(String key, String jsonString) {
		List<String> list = new ArrayList<String>();

		try {
			JSONObject jsonObject = new JSONObject(jsonString);
			JSONArray StringArray = jsonObject.getJSONArray(key);
			for (int i = 0; i < StringArray.length(); i++) {
				String str = StringArray.getString(i);
				list.add(str);

			}

		} catch (Exception e) {
			// TODO: handle exception
		}

		return list;

	}

	public static List<Map<String, Object>> getMaps(String key,
			String jsonString) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

		try {
			JSONObject jsonObject = new JSONObject(jsonString);
			JSONArray mapsArray = jsonObject.getJSONArray(key);
			for (int i = 0; i < mapsArray.length(); i++) {
				JSONObject jsonObject2 = mapsArray.getJSONObject(i);
				Map<String, Object> map = new HashMap<String, Object>();
				// 查看Map中的键值对的key值
				Iterator<String> iterator = jsonObject2.keys();

				while (iterator.hasNext()) {
					String json_key = iterator.next();
					Object json_value = jsonObject2.get(json_key);
					if(json_value==null){
						//当键值对中的value为空值时,将value置为空字符串;
						json_value="";
					}
					map.put(json_key, json_value);
				}
				list.add(map);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return list;
	}

}

需要注意的是上述,客户端和服务器端虽然都用到了JSONObject类,但是引用的不是一个jar包中的内容哦;客户端的是引用的org.json.JSONObject;而服务器端引用的是net.sf.json.JSONObject;
(关于gson解析,和fastjson解析json数据有时间再补,今天就先写到这儿了)

关于Gson解析请移步到这 Andorid之Gson解析Json数据

Q.E.D.


寻门而入,破门而出