2. JSONObject:json对象,{key:value}
构造方法JSONObject()、JSONObject(Map map)、JSONObject(String str)等普通方法:增加:accumulate(key,value)、put(key,value)删除:clear()、remove(key)查询:get(key)、isEmpty()、containsKey(key)、size()其他:fromObject(Object)对象转json,JSONObject转对象:toBean(JSONObject,Class) @Test public void testJSONObject(){ JSONObject jsonObj = new JSONObject(); jsonObj.put("1", "一"); jsonObj.put("2", "二"); jsonObj.accumulate("3", "三"); System.out.println(jsonObj.toString());//{"1":"一","2":"二","3":"三"} System.out.println(jsonObj.containsKey("1"));//true //转为Set集合 Set entrySet = jsonObj.entrySet(); Iterator iterator = entrySet.iterator(); while(iterator.hasNext()){ System.out.println(iterator.next());//1=一 2=二 3=三 } System.out.println(jsonObj.size());//3 //Java对象转Json JSONObject fromObject2 = JSONObject.fromObject(new Student(1,"haha","heihei")); //JSONObject转对象 Student student = (Student)JSONObject.toBean(fromObject2,Student.class); System.out.println(student);//Student [id=1, name=haha, sex=heihei] System.out.println(fromObject2);//{"sex":"heihei","name":"haha","id":1} //测试JSONArray,JSONArray里面存的是JSONObject //JSONArray,json数组,使用[],里面是一条条json格式的数据 JSONArray jsonArr = new JSONArray(); JSONObject jsonObj2 = new JSONObject(); jsonObj2.put("1", "一"); jsonObj2.put("2", "二"); jsonObj2.accumulate("3", "三"); jsonArr.add(jsonObj); jsonArr.add(jsonObj2); System.out.println(jsonArr);//[{"1":"一","2":"二","3":"三"},{"1":"一","2":"二","3":"三"}] }