日期:2014-05-16  浏览次数:20356 次

JSONObject和JSONArray对象的创建方法

1.json-lib-2.4-jdk15及其依赖jar包 ,需要注意的是所依赖jar包之间的兼容性,仅仅是导入json-lib是不够的 ,包括commons-logging-1.1.1.jar日志包,xom (XOM ? 是一种新的 XML 对象模型。 它是一个开源 (LGPL),用于处理 XML 和 Java 力求正确性、 简单化和性能,在这基于树的 API)等


2.JSONOBject对象的创建,基于JSONobject的静态方法fromObject进行创建

??? 1.通过JSONObject()构造函数创建JSON对象

JSONObject jObject = new JSONObject();
		 /*
		  * json对象添加数据的三种方式
		  * 	--|public Object put(Object,key,Object value)
		  *     --|public JSONObject accumulate (String key, Object value) 
		  *     --|public JSONObject element (String key, Object value) 
		  */
		 //通过element往jObject对象中添加数据,如果key为Null,将会移除当前key
		 jObject.element("name", "zhangsan");
		 jObject.element("sex", "girl");
		 jObject.element("age", 16);
		 
		 //关联一个key得到与之对应的value值
		 System.out.println(jObject.get("name"));
		 System.out.println(jObject.getInt("age"));
		//如果key为null,则返回值为null,并不会抛异常
		 System.out.println(jObject.get("work"));  
		 
		 
		 JSONObject jsonObject = new JSONObject()
		 							.element("string", "JSON")   
									.element("integer", "1")
									.element("double", "2.0")
									.element("boolean", "true");
	
?

?

?

? 2.静态方法fromObject()的调用,使用格式化json字符串来创建jsonobject对象

?

String jsonStr = "{\"age\":12,\"name\":\"wangwu\"}";
		 JSONObject jsonOb = JSONObject.fromObject(jsonStr);
		System.out.println(jsonOb.toString());
		
		String jsonstr1 = "{\"age\":17,\"integer\":1,\"boolean\":true,\"double\":2.0}";
		JSONObject json = (JSONObject) JSONSerializer.toJSON(jsonstr1);
		System.out.println(json.getInt("integer"));
		System.out.println(json.getDouble("double"));
		System.out.println(json.getString("age"));
		System.out.println(json.getBoolean("boolean"));
                bject.getInt("age"));
		//如果key为null,则返回值为null,并不会抛异常
		 System.out.println(jObject.get("work"));  
		 
		 
		 JSONObject jsonObject = new JSONObject()
		 							.element("string", "JSON")   
									.element("integer", "1")
									.element("double", "2.0")
?

? 3.使用一个map来创建JSONObject对象

?

?

                Map<String,Object> map = new HashMap<String, Object&