JSONObject类的常用方法
public class JSONObjectDemo01 {
public static void main(String[] args) {
Course course1 = new Course(1, "语文");
Course course2 = new Course(2, "数学");
List<Course> list = new ArrayList<Course>();
list.add(course1);
list.add(course2);
Student student = new Student(1, "张三", 15, new Date());
Date date = new Date();
JSONObject obj = new JSONObject();
//JSONObject实现了Map接口,主要操作方法是put方法
obj.put("student1", student);
obj.put("student2", student);
obj.put("list", list);
obj.put("date", date);
System.out.println(obj);
// 默认输出格式:相同的student对象,第二个的对象的内容变成了引用,时间为毫秒数
// {"student2":{"age":15,"birth":1437636491413,"name":"张三","studentId":1},"student1":{"$ref":"$.student2"},"list":[{"courseId":1,"courseName":"语文"},{"courseId":2,"courseName":"数学"}],"date":1437636491413}
//获取日期类型
Date date2 = obj.getDate("date");
//获取自定义类型
Student student2 = obj.getObject("student1", Student.class);
//获取 JSONArray类型
JSONArray array = obj.getJSONArray("list");
System.out.println(date2 + "\n" + student2.getBirth() + "\n" + array);
/**
* 输出结果
* Thu Jul 23 15:28:11 CST 2015
* Thu Jul 23 15:28:11 CST 2015
* [{"courseName":"语文","courseId":1},{"courseName":"数学","courseId":2}]
*/
}
}
JSONArray常用方法
public class JSONArrayDemo01 {
public static void main(String[] args) {
Course course1 = new Course(1, "语文");
Course course2 = new Course(2, "数学");
Course course3 = new Course(3, "物理");
Course course4 = new Course(4, "化学");
JSONArray array = new JSONArray();
// JSONArray实现了List接口,主要方法是add方法
array.add(course1);
array.add(course2);
List<Object> list = new ArrayList<>();
list.add(course3);
list.add(course4);
// JSONArray有参构造
JSONArray array2 = new JSONArray(list);
System.out.println(array + "\n" + array2);
// 输出结果
// [{"courseId":1,"courseName":"语文"},{"courseId":2,"courseName":"数学"}]
// [{"courseId":3,"courseName":"物理"},{"courseId":4,"courseName":"化学"}]
Course course5 = array2.getObject(0, Course.class);
System.out.println(course5);
JSONObject obj = array2.getJSONObject(1);
System.out.println(obj);
// 输出结果
// Course [courseId=3, courseName=物理]
// {"courseName":"化学","courseId":4}
}
}