json-lib 简单使用

		/**
		 * json-lib 下载地址
		 * http://sourceforge.net/projects/json-lib/
		 */
		
		/**
		 * java map 转换为  json串
		 */
		Map user = new HashMap();
		user.put("name", "张三");
		user.put("old", "23");
		
		//map 等同 bean 对待,使用 JSONObject
		JSONObject jsonObject = JSONObject.fromObject(user);
		String map_json_str = jsonObject.toString();
		System.out.println(map_json_str);
		//打印结果:{"old":"23","name":"张三"}
		
		/**
		 * json 串还原为java map
		 */
		jsonObject = JSONObject.fromObject(map_json_str);
		user = (Map)JSONObject.toBean(jsonObject, HashMap.class);
		System.out.println(user);
		//打印结果:{old=23, name=张三}
		
		/**
		 * java 数组 转换为  json串
		 */
		String countryArray[] = {"英国","法国","德国"};
		JSONArray jsonArray = JSONArray.fromObject(countryArray);
		String array_json_str = jsonArray.toString();
		System.out.println(array_json_str);
		//打印结果:["英国","法国","德国"]
		
		/**
		 * json 串还原为 java 数组
		 */
		jsonArray = JSONArray.fromObject(array_json_str);
		Object[] countryArrayObj = jsonArray.toArray();
		for (int i = 0; i < countryArrayObj.length; i++) {
			System.out.print(countryArrayObj[i]+",");
		}
		//打印结果:英国,法国,德国,
		
		/**
		 * java list 转换为  json串
		 */
		List countryList = new ArrayList();
		countryList.add("中国");
		countryList.add("美国");
		countryList.add("俄罗斯");
		
		//list 等同 数组对待,使用 JSONArray
		jsonArray = JSONArray.fromObject(countryList);
		String list_json_str = jsonArray.toString();
		System.out.println(list_json_str);
		//打印结果:["中国","美国","俄罗斯"]

		/**
		 * json 还原为 list
		 */
		jsonArray = JSONArray.fromObject(list_json_str);
		countryList = JSONArray.toList(jsonArray, new Object(), null);
		System.out.println(countryList);
		//打印结果:[中国, 美国, 俄罗斯]
		
		/**
		 * java list<Map> 转换为 json 串
		 */
		Map user2 = new HashMap();
		user2.put("name", "李四");
		user2.put("old", "24");
		List<Map> userList = new ArrayList<Map>();
		userList.add(user);
		userList.add(user2);
		jsonArray = JSONArray.fromObject(userList);
		String json_list_map_str = jsonArray.toString();
		System.out.println(json_list_map_str);
		//打印结果:[{"old":"23","name":"张三"},{"old":"24","name":"李四"}]
		
		/**
		 * json 串还原为 java list<map>
		 */
		jsonArray = JSONArray.fromObject(json_list_map_str);
		userList = JSONArray.toList(jsonArray, new HashMap(), new JsonConfig());
		System.out.println(userList);
		//打印结果:[{old=23, name=张三}, {old=24, name=李四}]

 http://huangqiqing123.iteye.com/blog/1899608

你可能感兴趣的:(json)