json-lib与org.json与gson三种方法解析数组json数据

import java.util.Iterator;

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

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

/**
 *@Author:liangjilong
 *@Date:2014-2-24
 *@Version:1.0
 *@Description:
 */
public class JsonTest {

	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {

		//String json="[{\"id\":1,\"userName\":\"liangjilong\"},{\"id\":2,\"userName\":\"梁继龙\"}]";
		
		String json="";;
		StringBuilder buffer=new StringBuilder();
		buffer.append("[");
			buffer.append("{");
			buffer.append("'id'").append(":").append(1);
				buffer.append(",");
			buffer.append("'userName'").append(":").append("'liangjilong'");
			buffer.append("}");
		buffer.append(",");
			buffer.append("{");
			buffer.append("'id'").append(":").append(2);
				buffer.append(",");
			buffer.append("'userName'").append(":").append("'梁继龙'");
			buffer.append("}");
		buffer.append("]");
		
		json=buffer.toString();
		
		
		/*******************json-lib-2.2-jdk15.jar***********************/
		JSONArray jarr1=JSONArray.fromObject(json);
		for (int i = 0; i < jarr1.size(); i++) {
			JSONObject jo=(JSONObject)jarr1.get(i);
			System.out.println(jo.get("id"));
			System.out.println(jo.get("userName"));
		}
		
		
		/*******************org.json.jar***********************/
		org.json.JSONArray jarr2=new org.json.JSONArray(json);
		for (int y = 0; y < jarr2.length(); y++) {
			org.json.JSONObject jo=(org.json.JSONObject)jarr2.get(y);
			System.out.println(jo.get("id"));
			System.out.println(jo.get("userName"));
		}
			
	 
		/*******************gson-2.2.4.jar***********************/
		JsonElement jsonEl = new JsonParser().parse(json);
		JsonArray jarr3= jsonEl.getAsJsonArray();
		for (Iterator iterator = jarr3.iterator(); iterator.hasNext();) {
			JsonObject object = (JsonObject) iterator.next();
			String id=object.get("id").getAsString();
			String userName=object.get("userName").getAsString();
			System.out.println(id+"\t"+userName);
			
		}
		
	}

}

 

你可能感兴趣的:(json)