java处理json数据格式

首先下载json-simple-1.1.jar包

主要的类为:JSONArray,JSONObject,JSONValue

代码示例:
public static void testJSON() {
		String jsString = "[\"129653\",\"129664\",\"129660\",\"129665\"]";
		//解析json数组字符串
		JSONArray ja = (JSONArray)JSONValue.parse(jsString);
		for(int i = 0; i < ja.size(); i++) {
			System.out.println(ja.get(i) + ":::");
		}
		//生成JSONArray数组
		JSONArray new_ja = new JSONArray();
		new_ja.add("aaaa");
		new_ja.add("bbbb");
		new_ja.add("cccc");
		System.out.println(new_ja.toJSONString());
		
		//解析json字符
		String objString = "{\"aa\":1,\"cc\":2,\"bb\":3}";
		JSONObject jo = (JSONObject)JSONValue.parse(objString);
		Iterator iter = jo.keySet().iterator();
		while(iter.hasNext()) {
			String key = iter.next().toString();
			System.out.println("[key=" + key + ", val=" + jo.get(key) + "]");
		}
		
		//生成JSONObject对象
		JSONObject new_jo = new JSONObject();
		new_jo.put("bbb", "ddd");
		new_jo.put("bbb0", 1);
		new_jo.put("bbb1", 11);
		new_jo.put("bbb12", "asflex");
		System.out.println(new_jo.toJSONString());
	}

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