java 方式的将 java 对象以及 list 或者 map 转化为 json 数据
JavajsonAjax.net
学会了在
j2ee中使用ajax后,
有时候从服务器返回客户端的数据是对象,自己手动拼凑
json
字符串容易出错,
通过谷歌知道了
json-lib
这个类库,
方便的支持
java
中对象到
json
字符串的转化。
看
source-forge
的
json-lib
介绍说,需要
jakartacommons-lang2.4
jakartacommons-beanutils1.7.0
jakartacommons-collections3.2
jakartacommons-logging1.1.1
ezmorph1.0.6这些jar
包的支持,下载下来试了一把,挺好用的,写出来,与大家分享。
代码如下:
importjava.util.ArrayList;
importjava.util.HashMap;
importjava.util.List;
importjava.util.Map;
importnet.sf.json.JSONArray;
importnet.sf.json.JSONObject;
publicclassTest{
publicstaticvoidmain(String[]args){
//
当是对象的时候
Studentstudent=newStudent();
student.setAge(18);
student.setName("zhangsan");
student.setSex("male");
JSONObjectjsonObject=JSONObject.fromObject(student);
System.out.println(jsonObject);//
输出
{"age":18,"name":"zhangsan","sex":"male"}
//
当是数组或
list
的时候
Student[]stus=newStudent[5];
List<Student>stuList=newArrayList<Student>();
for(inti=0;i<stus.length;i++){
stus[i]=newStudent();
stus[i].setAge(i*10+8);
stus[i].setName("zhang"+i);
stus[i].setSex("male");
//
添加到
list,
一会儿用
stuList.add(stus[i]);
}
JSONArrayjsonArray=JSONArray.fromObject(stus);
System.out.println(jsonArray);//
和下面打印的结果相同
//
结
果
:
[{"age":8,"name":"zhang0","sex":"male"},{"age":18,"name":"zhang1","sex":"male"},{"a
ge":28,"name":"zhang2","sex":"male"},{"age":38,"name":"zhang3","sex":"male"},{"ag
e":48,"name":"zhang4","sex":"male"}]
JSONArrayjsonArrayFromList=JSONArray.fromObject(stuList);
System.out.println(jsonArrayFromList);//
和上面打印的结果相同
//
当既有对象又有数组的时候
Map<String,Object>map=newHashMap<String,Object>();
Teacherteacher=newTeacher();
teacher.setAge(30);
teacher.setName("laoshi");
teacher.setSex("male");
map.put("teacher",teacher);
map.put("student",stuList);
JSONObjectjsonObjectFromMap=JSONObject.fromObject(map);
System.out.println(jsonObjectFromMap);
//
结果:
//{"student":[{"age":8,"name":"zhang0","sex":"male"},{"age":18,"name":"zhang1","se
x":"male"},{"age":28,"name":"zhang2","sex":"male"},{"age":38,"name":"zhang3","sex"
:"male"},{"age":48,"name":"zhang4","sex":"male"}],"teacher":{"age":30,"name":"laosh
i","sex":"male"}}
}
}