1.json的基本语法
1.表示一个对象
{"name":'"zhangsan","age":22}
{"name":"lisi","addr":{"city":"jinan","street":"huayuanlu"}}
属性名要添加引号
属性值如果是字符串,要添加引号
数据类型:string,number,boolean,null,object
2.表示一个对象数组
[{},{},{}]
2.Java处理json
1.首先引入json的jar包
2.
// 对象转换为json字符串
Student st = new Student();
st.setId(1);
st.setAge(22);
st.setName("张三s");
st.setAddr("jinan");
JSONObject obj = JSONObject.fromObject(st);
String str = obj.toString();
System.out.println(str);// {"addr":"jinan","age":22,"id":1,"name":"张三s"}
// 数组对象转换位json字符串
Student s1 = new Student(2, 22, "李四", "济宁");
Student s2 = new Student(3, 23, "王五", "青岛");
Student s3 = new Student(4, 24, "赵六", "上海");
Student[] ssarr = { s1, s2, s3 };
JSONArray obj1 = JSONArray.fromObject(ssarr);
String str1 = obj1.toString();
System.out.println(str1);
// list对象转换为json字符串
Student s11 = new Student(2, 22, "李四1", "济宁1");
Student s22 = new Student(3, 23, "王五1", "青岛1");
Student s33 = new Student(4, 24, "赵六1", "上海1");
List<Student> sslist = new ArrayList<Student>();
sslist.add(s11);
sslist.add(s22);
sslist.add(s33);
JSONArray obj2 = JSONArray.fromObject(sslist);
String str2 = obj2.toString();
System.out.println(str2);
3.json处理日期
原始的处理方法得到的是日期对象的json字符串
{"date":15,"day":5,"hours":11,"minutes":31,"month":10,"seconds":9,"time":1384486269320,"timezoneOffset":-480,"year":113}
1.首先写一个日期处理器工具类 implements JsonValueProcessor
public class DateProcessor implements JsonValueProcessor {
String pattern ="yyyy-MM-dd";
@Override
public Object processArrayValue(Object arg0, JsonConfig arg1) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.format((Date) arg0);
}
@Override
public Object processObjectValue(String arg0, Object arg1, JsonConfig arg2) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.format((Date) arg1);
}
}
2.在对象转json的时候加上config参数
// json处理日期
JsonConfig config = new JsonConfig();
config.registerJsonValueProcessor(Date.class, new DateProcessor());
Student dd = new Student(2, 22, "李四1", "济宁1", new Date());
JSONObject obj3 = JSONObject.fromObject(dd,config);
String str3 = obj3.toString();
System.out.println(str3);
这样之后日期就是一个字符串了
"2013-11-15"