json

JSONObject的总结:
  JSONObject需要以下几个包(见附件):
       1.commons-lang.jar
      2.commons-beanutils.jar
      3.commons-collections.jar
      4.commons-logging.jar
      5.ezmorph.jar
      6.json-lib-2.2.2-jdk15.jar 

若使用时报如下错:
  1、报java.lang.NoClassDefFoundError: net/sf/ezmorph/Morpher异常时,是缺少ezmorph.jar文件,如果有这个包就是版本不对,重新加载一个。
  2、报java.lang.NoClassDefFoundError: /apache/commons
/collections/map/ListOrderedMap异常时,是缺少commons-collections.jar文件,若存在则为版本不对。

以下为简单应用:
1.list转化为json
JSONArray.fromObject(Object o,String[]str);
说明:o为list时,且o中是类对象,str不需要转化成json格式的属性。
例:
   List stuList = new ArrayList();
for (int i = 0; i < 4; i++) {
     OvertimeTaskForm o= new OvertimeTaskForm();
     o.setDeptId("1"+i);
     o.setOvertimeTask("12"+i);
     o.setPracticetime("123"+i);
      //添加到list
       stuList.add(o);
     }
String[] str= {"processType","processStatus"}; //不需要转化的对象属性
     JSONArray jsonArray = JSONArray.fromObject(stuList,str);
     System.out.println(jsonArray);
2、Bean转换成json
   JSONObject.fromBean(Object bean,String arg[])
说明:把类bean属性转换成一个JSON数据格式,arg是指定那些属性不需要转换。
例: 说明:PersonBean的属性 Id name age
             PersonBean bean = new PersonBean();
bean.setId("0001");
bean.setName("pyt");
bean.setAge(10);
JSONObject jo = JSONObject.fromBean(bean);
System.out.println(jo);

输出:{"id":"0001","name":"pyt","age":10}
3、Map转换成json
   Map map = new HashMap();
map.put("1", "一号");
map.put("2","二号");
map.put("3", "三号");
JSONObject jo = JSONObject.fromMap(map);
System.out.println(jo);
输出:{"3":"三号","2":"二号","1":"一号"}

你可能感兴趣的:(json)