1.JSONObject 的常用方法
//数据准备
List<Student> list=new ArrayList<Student>();
list.add(new Student(1,1000d,"旅游",new Date()));
list.add(new Student(2,1500d,"玩电脑游戏",new Date()));
list.add(new Student(3,3000d,"看电影",new Date()));
Student student=new Student(1,1000d,"旅游",new Date());
JSONObject jsonObject=new JSONObject();
jsonObject.put("8", "签名");
jsonObject.put("d", 10.0);
jsonObject.put("date", new Date());
jsonObject.put("stu", new Student(8,8000d,"购物",new Date()));
jsonObject.put("arr", list);
//相当于
Map<String,Object> map=new HashMap<String, Object>();
//常用方法
//1.判断该JSONObject对象是否为空
jsonObject.isEmpty();
//2.获取键值对的数量
jsonObject.size();
//3.根据键获取value;
jsonObject.get("1");
jsonObject.getString("8");
jsonObject.getDouble("d");
Date date = jsonObject.getDate("date");
System.out.println(date);
//4.是否包含指定的key
jsonObject.containsKey("1");
//5.是否包含指定的value
jsonObject.containsValue("签名");
//6.根据key获取对应的JSONObject对象
System.out.println(jsonObject);
JSONObject stuJson=jsonObject.getJSONObject("stu");
stuJson.put("bz", "好学生");
stuJson.put("hobby", "学习");
jsonObject.put("stu", stuJson);
System.out.println(stuJson);
System.out.println(jsonObject);
//7.根据key获取对应的JSONObject数组
JSONArray arrJson=jsonObject.getJSONArray("arr");
相当于List<Object> list=new ArrayList<Object>();
//8.将数组转换为list
List<Student> javaList = jsonObject.getJSONArray("arr").toJavaList(Student.class);
System.out.println(arrJson);
//9.将JSONObject转为json字符串
String jsonString = jsonObject.toJSONString();
System.out.println(jsonString);
//10.public class JSONObject extends JSON implements Map<String, Object>, Cloneable, Serializable, InvocationHandler{}
//具有map的特点
Set<Entry<String, Object>> entrySet = jsonObject.entrySet();
Iterator<Entry<String, Object>> iterator = entrySet.iterator();
while(iterator.hasNext()){
Entry<String, Object> next = iterator.next();
System.out.println(next.getKey()+":"+next.getValue());
}
Set<String> keySet = jsonObject.keySet();
Collection<Object> values = jsonObject.values();
//11.根据key移除键值对
jsonObject.remove("arr");
//12.清楚所有的元素
jsonObject.clear();
2.相关转换
JSONObject----》JSON字符串
JSONObject jsonObject=new JSONObject();
jsonObject.put("date", new Date());
//JSONObject--->json 字符串
String jsonString = jsonObject.toJSONString();
//JSONObject--->json 字符串
String string = jsonObject.toString();
JavaBean----》JSONObject
//javaBen--->JSONObject
//1.将javaBen转换为JSON字符串
String jsonString2 = JSONObject.toJSONString(student);
//2.JSON字符串---》JSONObject
JSONObject parseObject = JSONObject.parseObject(jsonString2);
JSONObject------》JavaBean
//JSONObject---->JavaBen
Student javaObject = JSONObject.toJavaObject(parseObject, Student.class);