JSON解析
//创建JSON的方法一
public static String creatJson(){
JSONObject obj = new JSONObject();
obj.put("name", "张三");
obj.put("num", "01");
JSONObject obj1 = new JSONObject();
obj1.put("name", "李四");
obj1.put("num", "02");
JSONObject obj2 = new JSONObject();
obj2.put("name", "王五");
JSONArray array = new JSONArray();
array.add(obj);
array.add(obj1);
array.add(obj2);
JSONObject clazz = new JSONObject();
clazz.put("clazzname", "三年二班");
clazz.put("num", "3");
clazz.put("student",array);
System.out.println(clazz.toString());
return obj.toString();
}
//创建JSON的方法二
Student zhangsan = new Student (20,"张三");
Student lisi = new Student(19,"李四");
Student wangwu = new Student(18,"王五");
JSONObject obj = new JSONObject();
JSONArray array = new JSONArray();
array.add(zhangsan);
array.add(lisi);
array.add(wangwu);
obj.put("student",array);
System.out.println(obj.toString());
return obj.toString();
}
运行结果:
{“student”:[{“age”:20,”name”:”张三”},{“age”:19,”name”:”李四”},{“age”:18,”name”:”王五”}]}
//JSON解析
// TODO Auto-generated method stub
String json = creatJson();
if(null!=json){
JSONObject clazz = JSONObject.fromObject(json);
System.out.println(clazz.getString("clazzname"));
JSONArray array = clazz.getJSONArray("student");
for (int i = 0; i < array.size(); i++) {
JSONObject obj = array.getJSONObject(i);
System.out.println(obj.getString("name"));
}
}
类
Date类
Calendar 类是一个抽象类,它为特定瞬间与一组诸如 YEAR、MONTH、DAY_OF_MONTH、HOUR 等 日历字段之间的转换提供了一些方法,并为操作日历字段(例如获得下星期的日期)提供了一些方法。
Calendar 方法摘要
getInstance() 使用默认时区和语言环境获得一个日历
add(int field, int amount) 根据日历的规则,为给定的日历字段添加或减去指定的时间量。
//在当前时间上加120秒
Calendar calendar = Calendar.getInstance();
calendar.add(calendar.SECOND, 120);
get(int field) 返回给定日历字段的值
calender.getTime()得到Date的时间
toString() 返回此日历的字符串表示形式。
类 SimpleDateFormat
SimpleDateFormat 是一个以与语言环境有关的方式来格式化和解析日期的具体类。它允许进行格式化(日期 -> 文本)、解析(文本 -> 日期)和规范化。
//自己定义日期的格式,将传入的字符串解析,得到小时数
String s = "2015/07/24 11/42/55";
SimpleDateFormat simple = new SimpleDateFormat("yyyy/MM/dd HH/mm/ss");
try {
Date date = simple.parse(s);
System.out.println(date.getHours());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
集合框架
ArrayList:
List<Student> students = new ArrayList<Student>();
Student zhangsan = new Student (20,"张三");
Student lisi = new Student (25,"李四");
Student wangwu = new Student (19,"王五");
students.add(wangwu);
students.add(lisi);
students.add(zhangsan);
students.add(zhangsan);
students.remove(2);