JSONObject介绍与操作

JSONObject是JSON-lib提供的一个解析JSON对象的工具类,它提供了多种在Java端解析JSON数据的方法。

代码:

public class JSONObj {
	
	public static void main(String[] args) {
		/**
		 * 通过字符串构建JSONObject
		 */
		JSONObject joFromString = new JSONObject();
		String str = "{\"Java\" : \"Hello Java\", \"C++\" : \"Hello C++\"}";
		joFromString = joFromString.fromObject(str);
		System.out.println("JSONObject------>fromObject(字符串): " + joFromString);
		
		System.out.println("____________________________________________________");
		
		/**
		 * 通过Map构建JSONObject
		 */
		JSONObject joFromMap = new JSONObject();
		Map map = new HashMap();
		map.put("张明", 22);
		map.put("李强", 23);
		joFromMap = joFromMap.fromObject(map);
		System.out.println("JSONObject------>fromObject(Map): " + joFromMap);
		
		System.out.println("____________________________________________________");
		
		/**
		 * 通过对象构建JSONObject
		 */
		JSONObject joFromObject = new JSONObject();
		joFromObject = joFromObject.fromObject(new Person("朱天",25));
		System.out.println("JSONObject------>fromObject(对象): " + joFromObject);
		
		System.out.println("____________________________________________________");
		
		/**
		 * 通过put方法构造JSONObject
		 */
		JSONObject joFromPut = new JSONObject();
		joFromPut.put("你", "在哪");
		joFromPut.put("我", "在这");
		System.out.println("JSONObject------>put(key,value): " + joFromPut);
		
		System.out.println("____________________________________________________");
		
	}

}

输出:

JSONObject介绍与操作_第1张图片

方法介绍:

put(Object key, Object value) 往JSONObject对象中添加数据

fromObject(Object object)将JSON格式字符串、Map、bean等转化为JSONObject对象








你可能感兴趣的:(java,JSONObject)