杭州建设银行网站,莒县城乡建设局网站,wordpress主题的网站,建设网站市场分析学会了在j2ee中使用ajax后,有时候从服务器返回客户端的数据是对象#xff0c;自己手动拼凑json字符串容易出错#xff0c;通过谷歌知道了json-lib这个类库#xff0c;方便的支持java中对象到json字符串的转化。看source-forge的json-lib介绍说#xff0c;需要jakarta commo…学会了在j2ee中使用ajax后,有时候从服务器返回客户端的数据是对象自己手动拼凑json字符串容易出错通过谷歌知道了json-lib这个类库方便的支持java中对象到json字符串的转化。看source-forge的json-lib介绍说需要jakarta commons-lang 2.4jakarta commons-beanutils 1.7.0jakarta commons-collections 3.2jakarta commons-logging 1.1.1ezmorph 1.0.6这些jar包的支持下载下来试了一把挺好用的写出来与大家分享。代码如下import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import net.sf.json.JSONArray;import net.sf.json.JSONObject;public class Test {public static void main(String[] args) {//当是对象的时候Student student new Student();student.setAge(18);student.setName(zhangsan);student.setSex(male);JSONObject jsonObject JSONObject.fromObject(student);System.out.println(jsonObject);//输出{age:18,name:zhangsan,sex:male}//当是数组或list的时候Student[] stus new Student[5];List stuList new ArrayList();for (int i 0; i stus.length; i) {stus[i] new Student();stus[i].setAge(i*108);stus[i].setName(zhangi);stus[i].setSex(male);//添加到list,一会儿用stuList.add(stus[i]);}JSONArray jsonArray JSONArray.fromObject(stus);System.out.println(jsonArray);//和下面打印的结果相同//结果[{age:8,name:zhang0,sex:male},{age:18,name:zhang1,sex:male},{age:28,name:zhang2,sex:male},{age:38,name:zhang3,sex:male},{age:48,name:zhang4,sex:male}]JSONArray jsonArrayFromList JSONArray.fromObject(stuList);System.out.println(jsonArrayFromList);//和上面打印的结果相同//当既有对象又有数组的时候Map map new HashMap();Teacher teacher new Teacher();teacher.setAge(30);teacher.setName(laoshi);teacher.setSex(male);map.put(teacher, teacher);map.put(student, stuList);JSONObject jsonObjectFromMap JSONObject.fromObject(map);System.out.println(jsonObjectFromMap);//结果//{student:[{age:8,name:zhang0,sex:male},{age:18,name:zhang1,sex:male},{age:28,name:zhang2,sex:male},{age:38,name:zhang3,sex:male},{age:48,name:zhang4,sex:male}],teacher:{age:30,name:laoshi,sex:male}}}}