JSON-lib 使用

来源:互联网 发布:淘宝包邮是怎么做到的 编辑:程序博客网 时间:2024/06/08 02:39

http://weishuwei.iteye.com/blog/97384

json-lib.jar开发包使用:

依赖包:
commons-beanutils.jar;
commons-httpclient.jar;
commons-lang.jar;
ezmorph.jar;不少人使用时会提示net.sf.ezmorph.xxx找不到,就是缺这个:
morph-1.0.1.jar

相关链接:
http://json-lib.sourceforge.net/
http://ezmorph.sourceforge.net/
http://morph.sourceforge.net/

使用过程中问题:
1,把bean转化为json格式时老提示如下错误:
Exception in thread "main" net.sf.json.JSONException: java.lang.NoSuchMethodException: Property 'name' has no getter method
解决:声明bean为public class xxx,必须是public,我用默认类型(class xxx)都不行

2,Exception in thread "main" java.lang.NoSuchMethodError: org.apache.commons.lang.ArrayUtils.toObject([C)[Ljava/lang/Character;
原因:定义属性如下:private char[] options = new char[] { 'a', 'f' };好像不能处理这种类型的

3, private String func1 = "function(i){ return this.options[i]; }";
   和
   private JSONFunction func2 = new JSONFunction(new String[] { "i" },
     "return this.options[i];");
   转换后显示结果差不多:
   {"func1":function(i){ return this.options[i];,"func2":function(i){ return this.options[i]; }}

测试类:
 
  1. import java.util.ArrayList;  
  2. import java.util.HashMap;  
  3. import java.util.List;  
  4. import java.util.Map;  
  5.   
  6. import net.sf.json.JSONArray;  
  7. import net.sf.json.JSONObject;  
  8.   
  9. public class Json {  
  10.     public static void main(String[] args) {  
  11.         Json j = new Json();  
  12.         j.bean2json();  
  13.     }  
  14.   
  15.     public void arr2json() {  
  16.         boolean[] boolArray = new boolean[] { truefalsetrue };  
  17.         JSONArray jsonArray = JSONArray.fromObject(boolArray);  
  18.         System.out.println(jsonArray);  
  19.         // prints [true,false,true]  
  20.     }  
  21.   
  22.     public void list2json() {  
  23.         List list = new ArrayList();  
  24.         list.add("first");  
  25.         list.add("second");  
  26.         JSONArray jsonArray = JSONArray.fromObject(list);  
  27.         System.out.println(jsonArray);  
  28.         // prints ["first","second"]  
  29.     }  
  30.   
  31.     public void createJson() {  
  32.         JSONArray jsonArray = JSONArray.fromObject("['json','is','easy']");  
  33.         System.out.println(jsonArray);  
  34.         // prints ["json","is","easy"]  
  35.     }  
  36.   
  37.     public void map2json() {  
  38.         Map
  39.         map.put("name""json");  
  40.         map.put("bool", Boolean.TRUE);  
  41.         map.put("int"new Integer(1));  
  42.         map.put("arr"new String[] { "a""b" });  
  43.         map.put("func""function(i){ return this.arr[i]; }");  
  44.   
  45.         JSONObject json = JSONObject.fromObject(map);  
  46.         System.out.println(json);  
  47.         // prints  
  48.         // ["name":"json","bool":true,"int":1,"arr":["a","b"],"func":function(i){  
  49.         // return this.arr[i]; }]  
  50.     }  
  51.   
  52.     public void bean2json() {  
  53.         JSONObject jsonObject = JSONObject.fromObject(new MyBean());  
  54.         System.out.println(jsonObject);  
  55.         /* 
  56.          * prints  
  57.          * {"func1":function(i){ return this.options[i]; 
  58.          * },"pojoId":1,"name":"json","func2":function(i){ return 
  59.          * this.options[i]; }} 
  60.          */  
  61.     }  
  62.   
  63.     public void json2bean() {  
  64.         String json = "{name=\"json2\",func1:true,pojoId:1,func2:function(a){ return a; },options:['1','2']}";  
  65.         JSONObject jb = JSONObject.fromString(json);  
  66.         JSONObject.toBean(jb, MyBean.class);  
  67.         System.out.println();  
  68.     }  
  69. }  

操作的bean:
 
  1. import net.sf.json.JSONFunction;  
  2.   
  3. public class MyBean {  
  4.     private String name = "json";  
  5.     private int pojoId = 1;  
  6.     // private char[] options = new char[] { 'a', 'f' };  
  7.     private String func1 = "function(i){ return this.options[i]; }";  
  8.     private JSONFunction func2 = new JSONFunction(new String[] { "i" },  
  9.             "return this.options[i];");  
  10.   
  11.     // getters & setters  
  12.     ......  
  13. }  

题外话: 这个我对json-lib包的初次尝试,希望对大家有所帮助,另外大家有谁用过其它处理json的开发包,提出来,大家探讨一下~!!!!
=============
java中使用net.sf.json对json进行解析
1869人阅读 评论(0)收藏举报

net.sf.json依赖的包很多。

有commons-collections,commons-beanutils.jar,commons-httpclient.jar,commons-lang.jar,ezmorph-1.0.5.jar,morph-1.1.1.jar

  1. /**  
  2.      * 从一个JSON 对象字符格式中得到一个java对象,形如: 
  3.      * {"id" : idValue, "name" : nameValue, "aBean" : {"aBeanId" : aBeanIdValue, ...}} 
  4.      * @param object  
  5.      * @param clazz  
  6.      * @return  
  7.      */  
  8.     public static Object getDTO(String jsonString, Class clazz){   
  9.         JSONObject jsonObject = null;   
  10.         try{   
  11.             setDataFormat2JAVA();    
  12.             jsonObject = JSONObject.fromObject(jsonString);   
  13.         }catch(Exception e){   
  14.             e.printStackTrace();   
  15.         }   
  16.         return JSONObject.toBean(jsonObject, clazz);   
  17.     }   
  18.        
  19.     /**  
  20.      * 从一个JSON 对象字符格式中得到一个java对象,其中beansList是一类的集合,形如: 
  21.      * {"id" : idValue, "name" : nameValue, "aBean" : {"aBeanId" : aBeanIdValue, ...}, 
  22.      * beansList:[{}, {}, ...]} 
  23.      * @param jsonString 
  24.      * @param clazz  
  25.      * @param map 集合属性的类型 (key : 集合属性名, value : 集合属性类型class) eg: ("beansList" : Bean.class) 
  26.      * @return  
  27.      */  
  28.     public static Object getDTO(String jsonString, Class clazz, Map map){   
  29.         JSONObject jsonObject = null;   
  30.         try{   
  31.             setDataFormat2JAVA();    
  32.             jsonObject = JSONObject.fromObject(jsonString);   
  33.         }catch(Exception e){   
  34.             e.printStackTrace();   
  35.         }   
  36.         return JSONObject.toBean(jsonObject, clazz, map);   
  37.     }   
  38.        
  39.     /**  
  40.      * 从一个JSON数组得到一个java对象数组,形如: 
  41.      * [{"id" : idValue, "name" : nameValue}, {"id" : idValue, "name" : nameValue}, ...] 
  42.      * @param object  
  43.      * @param clazz  
  44.      * @return  
  45.      */  
  46.     public static Object[] getDTOArray(String jsonString, Class clazz){   
  47.         setDataFormat2JAVA();   
  48.         JSONArray array = JSONArray.fromObject(jsonString);   
  49.         Object[] obj = new Object[array.size()];   
  50.         for(int i = 0; i < array.size(); i++){   
  51.             JSONObject jsonObject = array.getJSONObject(i);   
  52.             obj[i] = JSONObject.toBean(jsonObject, clazz);   
  53.         }   
  54.         return obj;   
  55.     }   
  56.        
  57.     /**  
  58.      * 从一个JSON数组得到一个java对象数组,形如: 
  59.      * [{"id" : idValue, "name" : nameValue}, {"id" : idValue, "name" : nameValue}, ...] 
  60.      * @param object  
  61.      * @param clazz  
  62.      * @param map  
  63.      * @return  
  64.      */  
  65.     public static Object[] getDTOArray(String jsonString, Class clazz, Map map){   
  66.         setDataFormat2JAVA();   
  67.         JSONArray array = JSONArray.fromObject(jsonString);   
  68.         Object[] obj = new Object[array.size()];   
  69.         for(int i = 0; i < array.size(); i++){   
  70.             JSONObject jsonObject = array.getJSONObject(i);   
  71.             obj[i] = JSONObject.toBean(jsonObject, clazz, map);   
  72.         }   
  73.         return obj;   
  74.     }   
  75.        
  76.     /**  
  77.      * 从一个JSON数组得到一个java对象集合 
  78.      * @param object  
  79.      * @param clazz  
  80.      * @return  
  81.      */  
  82.     public static List getDTOList(String jsonString, Class clazz){   
  83.         setDataFormat2JAVA();   
  84.         JSONArray array = JSONArray.fromObject(jsonString);   
  85.         List list = new ArrayList();   
  86.         for(Iterator iter = array.iterator(); iter.hasNext();){   
  87.             JSONObject jsonObject = (JSONObject)iter.next();   
  88.             list.add(JSONObject.toBean(jsonObject, clazz));   
  89.         }   
  90.         return list;   
  91.     }   
  92.        
  93.     /**  
  94.      * 从一个JSON数组得到一个java对象集合,其中对象中包含有集合属性 
  95.      * @param object  
  96.      * @param clazz  
  97.      * @param map 集合属性的类型 
  98.      * @return  
  99.      */  
  100.     public static List getDTOList(String jsonString, Class clazz, Map map){   
  101.         setDataFormat2JAVA();   
  102.         JSONArray array = JSONArray.fromObject(jsonString);   
  103.         List list = new ArrayList();   
  104.         for(Iterator iter = array.iterator(); iter.hasNext();){   
  105.             JSONObject jsonObject = (JSONObject)iter.next();   
  106.             list.add(JSONObject.toBean(jsonObject, clazz, map));   
  107.         }   
  108.         return list;   
  109.     }   
  110.        
  111.     /**  
  112.      * 从json HASH表达式中获取一个map,该map支持嵌套功能 
  113.      * 形如:{"id" : "johncon", "name" : "小强"} 
  114.      * 注意commons-collections版本,必须包含org.apache.commons.collections.map.MultiKeyMap 
  115.      * @param object  
  116.      * @return  
  117.      */  
  118.     public static Map getMapFromJson(String jsonString) {   
  119.         setDataFormat2JAVA();   
  120.         JSONObject jsonObject = JSONObject.fromObject(jsonString);   
  121.         Map map = new HashMap();   
  122.         for(Iterator iter = jsonObject.keys(); iter.hasNext();){   
  123.             String key = (String)iter.next();   
  124.             map.put(key, jsonObject.get(key));   
  125.         }   
  126.         return map;   
  127.     }   
  128.        
  129.     /**  
  130.      * 从json数组中得到相应java数组 
  131.      * json形如:["123", "456"] 
  132.      * @param jsonString 
  133.      * @return  
  134.      */  
  135.     public static Object[] getObjectArrayFromJson(String jsonString) {   
  136.         JSONArray jsonArray = JSONArray.fromObject(jsonString);   
  137.         return jsonArray.toArray();   
  138.     }   
  139.   
  140.   
  141.     /**  
  142.      * 把数据对象转换成json字符串 
  143.      * DTO对象形如:{"id" : idValue, "name" : nameValue, ...} 
  144.      * 数组对象形如:[{}, {}, {}, ...] 
  145.      * map对象形如:{key1 : {"id" : idValue, "name" : nameValue, ...}, key2 : {}, ...} 
  146.      * @param object  
  147.      * @return  
  148.      */  
  149.     public static String getJSONString(Object object) throws Exception{   
  150.         String jsonString = null;   
  151.         //日期值处理器  
  152.         JsonConfig jsonConfig = new JsonConfig();   
  153.         jsonConfig.registerJsonValueProcessor(java.util.Date.classnew JsonDateValueProcessor());   
  154.         if(object != null){   
  155.             if(object instanceof Collection || object instanceof Object[]){   
  156.                 jsonString = JSONArray.fromObject(object, jsonConfig).toString();   
  157.             }else{   
  158.                 jsonString = JSONObject.fromObject(object, jsonConfig).toString();   
  159.             }   
  160.         }   
  161.         return jsonString == null ? "{}" : jsonString;   
  162.     }