当前位置: 代码迷 >> JavaScript >> json 简略实例
  详细解决方案

json 简略实例

热度:109   发布时间:2012-10-07 17:28:51.0
json 简单实例

jar包:
commons-beanutils-1.7.0.jar
commons-collections-3.1.jar
commons-lang-2.5.jar
commons-logging-1.1.1.jar
ezmorph-1.0.3.jar
json-lib-2.4-jdk15.jar


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

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

public class JSONObjectSample {

	// 创建JSONObject对象
	private static JSONObject createJSONObject() {
		JSONObject jsonObject = new JSONObject();
		// 定义数组
		JSONArray array = new JSONArray();
		array.add(0, "aa");
		array.add(1, "bb");
		array.add("cc");
		// 定义map
		Map<String, String> ingredients = new HashMap<String, String>();
		ingredients.put("apples", "3kg");
		ingredients.put("sugar", "1kg");
		ingredients.put("pastry", "2.4kg");
		ingredients.put("bestEaten", "outdoors");
		//添加到属性
		jsonObject.put("name", "kevin");
		jsonObject.put("Max.score", new Integer(100));
		jsonObject.put("Min.score", new Integer(50));
		jsonObject.put("nickname", "picglet");
		jsonObject.element("array", array);
		jsonObject.element("ingredients", ingredients);
		return jsonObject;
	}

	public static void main(String[] args) {
		JSONObject jobj = JSONObjectSample.createJSONObject();
		// 输出jsonobject对象
		System.out.println("jobj==>" + jobj);

		// 判读输出对象的类型
		boolean isArray = jobj.isArray();
		boolean isEmpty = jobj.isEmpty();
		boolean isNullObject = jobj.isNullObject();
		System.out.println("isArray:" + isArray + " isEmpty:" + isEmpty
				+ " isNullObject:" + isNullObject);

		// 返回一个JSONArray对象
		JSONArray jsonArray = jobj.getJSONArray("array");
		System.out.println("返回一个JSONArray对象:" + jsonArray);
		
		//返回一个jsonObject对象(map)
		JSONObject jsonObject = jobj.getJSONObject("ingredients");
		System.out.println("返回一个JSONObject(map)对象:" + jsonObject);
		
		// 根据key返回一个字符串
		String jsonString = jobj.getString("name");
		System.out.println("返回一个字符串jsonString对象:" + jsonString);
		
		//便利JsonArray对象
		System.out.println("遍历JsonArray:");
		for(int i=0; i<jsonArray.size(); i++) {
			System.out.println(jsonArray.get(i));
		}
		
		//便利JsonObject(map)
		System.out.println("遍历JsonObject(map):");
		for(Iterator iter = jsonObject.keys(); iter.hasNext();) {
			String key = (String) iter.next();
			System.out.println(key + "--" + jsonObject.getString(key));
		}
		
	}
}
?
  相关解决方案