通过一个普通javabean,通过一些过滤字段,来生成json

由于项目中用json作为ExtJS传到程序中的数据格式,所以许多地方需要将javaBean转换成为json,或者将list,map转换为json。所以写了一个工具类来做这个工作。实现方式分为两种:

1. 通过一个普通javabean,通过一些过滤字段,来生成json

Java代码 复制代码
  1. private static <T> JSONObject ObjectToJSON(T t, String[] fields, boolean fieldKind){   
  2.         Field[] fs = t.getClass().getDeclaredFields();   
  3.         JSONObject jsonObject = new JSONObject();   
  4.   
  5.         for (Field field : fs) {   
  6.             String propertyName = field.getName();   
  7.             for (String f : fields) {   
  8.                 try {   
  9.                     if (propertyName.equals(f) == fieldKind) {   
  10.                         String methodName = "get"  
  11.                                 + propertyName.substring(01).toUpperCase()   
  12.                                 + propertyName.substring(1);   
  13.                         Method m = t.getClass().getMethod(methodName);   
  14.                         Object o = m.invoke(t);   
  15.                         jsonObject.put(field.getName(), o instanceof String ? transHTML((String)o) : o);   
  16.                     } else {   
  17.                         continue;   
  18.                     }   
  19.                 } catch (SecurityException e) {   
  20.                     throw new JSONUtilException(e);   
  21.                 } catch (NoSuchMethodException e) {   
  22.                     throw new JSONUtilException(e);   
  23.                 } catch (IllegalArgumentException e) {   
  24.                     throw new JSONUtilException(e);   
  25.                 } catch (JSONException e) {   
  26.                     throw new JSONUtilException(e);   
  27.                 } catch (IllegalAccessException e) {   
  28.                     throw new JSONUtilException(e);   
  29.                 } catch (InvocationTargetException e) {   
  30.                     throw new JSONUtilException(e);   
  31.                 }   
  32.             }   
  33.         }   
  34.         return jsonObject;   
  35.     }  

 第一个参数是需要转换的bean,第二个参数为过滤字段,第三个参数是是否需要过滤的字段。也就是说,fieldKind为true时说明生成的json只包含第二个参数中的这些字段。如果fieldKind为false,生成json不包含这些字段

 

2. 通过在javabean类的属性上用annotation来表示是否需要生成到json中,并且通过可以通过在字段上设置children annotation来定义嵌套

Java代码 复制代码
  1. @Target(ElementType.FIELD)   
  2. @Retention(RetentionPolicy.RUNTIME)   
  3. public @interface Json {   
  4.     String jsonName() default "";   
  5.     boolean children() default false;   
  6.     String childrenName() default "children";   
  7. }  
 
Java代码 复制代码
  1. /**  
  2.      * 将对象封装成{@link JSONObject}对象,对象中的每个属性必须有<b>get</b>方法且符合<b>JavaBean</b>的命名标准。  
  3.      * 通过Annotation来封装JSONObject,JSONObject只包含带有{@link @Json}注释的属性  
  4.      * 通过设置jsonName来改变JSONObject的keyName  
  5.      * 目前不支持对象中有实现Collection接口类型的属性,所以请不要把这种属性加上Annotation  
  6.      *   
  7.      * @author (Jessdy) 编写日期:May 9, 2008  
  8.      * @author (Jessdy) 更新日期:May 23, 2008 更新内容:支持对于同类型的对象的父子层级关系  
  9.      * @author (Jessdy) 更新日期:Jul 25, 2008 更新内容:对于json输出值的过滤方法  
  10.      *   
  11.      * @param <T>  
  12.      * @param t  
  13.      *            需要转换成JSONObject的对象  
  14.      * @return  
  15.      */  
  16.     @SuppressWarnings("unchecked")   
  17.     public static <T> JSONObject ObjectToJSONByAnnotation(T t) {   
  18.         Field[] fields = t.getClass().getDeclaredFields();   
  19.         JSONObject jsonObject = new JSONObject();   
  20.         for (Field field : fields) {   
  21.             if (field.getAnnotations().length != 0  
  22.                     && field.getAnnotation(Json.class) != null) {   
  23.                 try {   
  24.                     String propertyName = field.getName();   
  25.                     String methodName = "get"  
  26.                             + propertyName.substring(01).toUpperCase()   
  27.                             + propertyName.substring(1);   
  28.                     Method m = t.getClass().getMethod(methodName);   
  29.                     if (!field.getAnnotation(Json.class).children()) {   
  30.                         String keyName = notEmpty(field.getAnnotation(   
  31.                                 Json.class).jsonName()) ? field.getAnnotation(   
  32.                                 Json.class).jsonName() : field.getName();   
  33.                         Object o = m.invoke(t);   
  34.                         jsonObject.put(keyName, o instanceof String ? transHTML((String)o) : o);   
  35.                     } else {   
  36.                         List<T> children = (List<T>) m.invoke(t);   
  37.                         if (children == null) {   
  38.                             children = new ArrayList<T>();   
  39.                         }   
  40.                         JSONArray jsonArray = children == null ? null  
  41.                                 : new JSONArray();   
  42.                         for (T child : children) {   
  43.                             JSONObject jsonChild = ObjectToJSONByAnnotation(child);   
  44.                             jsonArray.put(jsonChild);   
  45.                         }   
  46.                         jsonObject.put(field.getAnnotation(Json.class)   
  47.                                 .childrenName(), jsonArray);   
  48.                     }   
  49.                 } catch (SecurityException e) {   
  50.                     throw new JSONUtilException(e);   
  51.                 } catch (NoSuchMethodException e) {   
  52.                     throw new JSONUtilException(e);   
  53.                 } catch (IllegalArgumentException e) {   
  54.                     throw new JSONUtilException(e);   
  55.                 } catch (JSONException e) {   
  56.                     throw new JSONUtilException(e);   
  57.                 } catch (IllegalAccessException e) {   
  58.                     throw new JSONUtilException(e);   
  59.                 } catch (InvocationTargetException e) {   
  60.                     throw new JSONUtilException(e);   
  61.                 }   
  62.             }   
  63.         }   
  64.         return jsonObject;   
  65.     }  

 以上就是主要代码,还有一个自定义的JSONUtilException。另外使用了jsonme.jar包作为json基础包。

Java代码 复制代码
  1. /**  
  2.      * 将对象封装成{@link JSONObject}对象,对象中的每个属性必须有get方法且符合JavaBean的命名标准。  
  3.      * 目前不支持对象中有实现Collection接口类型的属性  
  4.      *   
  5.      * @author (Jessdy) 编写日期:May 9, 2008  
  6.      *   
  7.      * @param <T>  
  8.      * @param t  
  9.      *            需要转换成JSONObject的对象  
  10.      * @return  
  11.      */  
  12.     public static <T> JSONObject ObjectToJSON(T t) {   
  13.         return ObjectToJSON(t, new String[] { "" });   
  14.     }   
  15.   
  16. /**  
  17.      * 将对象封装成{@link JSONObject}对象,对象中的每个属性必须有<b>get</b>方法且符合<b>JavaBean</b>的命名标准。  
  18.      * 目前不支持对象中有实现Collection接口类型的属性,所以请把这种属性加入到filter中  
  19.      *   
  20.      * @author (Jessdy) 编写日期:May 9, 2008  
  21.      *   
  22.      * @param <T>  
  23.      * @param t  
  24.      *            需要转换成JSONObject的对象  
  25.      * @param filters  
  26.      *            被过滤的属性字符数组  
  27.      * @return  
  28.      */  
  29.     public static <T> JSONObject ObjectToJSON(T t, String[] filters) {   
  30.         return ObjectToJSON(t, filters, false);   
  31.     }   
  32.        
  33.     /**  
  34.      * 将对象封装成{@link JSONObject}对象,对象中的每个属性必须有<b>get</b>方法且符合<b>JavaBean</b>的命名标准。  
  35.      *   
  36.      * @author (Jessdy)  
  37.      * 编写日期:Jul 23, 2008  
  38.      * @author (Jessdy) 更新日期:Jul 25, 2008 更新内容:对于json输出值的过滤方法  
  39.      *   
  40.      * @param <T>  
  41.      * @param t 需要转换成JSONObject的对象  
  42.      * @param includes 被包含的属性字符数组  
  43.      * @return  
  44.      */  
  45.     public static <T> JSONObject IObjectToJSON(T t, String[] includes){   
  46.         return ObjectToJSON(t, includes, true);   
  47.     }   
  48.   
  49.     /**  
  50.      * 将对象数组封装成{@link JSONArray}对象,对象中的每个属性必须有<b>get</b>方法且符合<b>JavaBean</b>的命名标准。  
  51.      *   
  52.      * @author (Jessdy) 编写日期:May 9, 2008  
  53.      *   
  54.      * @param <T>  
  55.      * @param ts  
  56.      *            需要转换成JSONArray的对象数组  
  57.      * @return  
  58.      */  
  59.     public static <T> JSONArray ArrayToJSON(T[] ts) {   
  60.         JSONArray jsonArray = new JSONArray();   
  61.         for (T t : ts) {   
  62.             jsonArray.put(ObjectToJSON(t));   
  63.         }   
  64.         return jsonArray;   
  65.     }   
  66.   
  67.     /**  
  68.      * 将对象数组封装成{@link JSONArray}对象,对象中的每个属性必须有<b>get</b>方法且符合<b>JavaBean</b>的命名标准。  
  69.      *   
  70.      * @author (Jessdy) 编写日期:May 9, 2008  
  71.      *   
  72.      * @param <T>  
  73.      * @param ts  
  74.      *            需要转换成JSONArray的对象数组  
  75.      * @param filters  
  76.      *            被过滤的属性字符数组  
  77.      * @return  
  78.      */  
  79.     public static <T> JSONArray ArrayToJSON(T[] ts, String[] filters) {   
  80.         JSONArray jsonArray = new JSONArray();   
  81.         for (T t : ts) {   
  82.             jsonArray.put(ObjectToJSON(t, filters));   
  83.         }   
  84.         return jsonArray;   
  85.     }   
  86.        
  87.     /**  
  88.      * 将对象数组封装成{@link JSONArray}对象,对象中的每个属性必须有<b>get</b>方法且符合<b>JavaBean</b>的命名标准。  
  89.      *   
  90.      * @author (Jessdy) 编写日期:May 9, 2008  
  91.      *   
  92.      * @param <T>  
  93.      * @param ts  
  94.      *            需要转换成JSONArray的对象数组  
  95.      * @param filters  
  96.      *            被过滤的属性字符数组  
  97.      * @return  
  98.      */  
  99.     public static <T> JSONArray IArrayToJSON(T[] ts, String[] includes) {   
  100.         JSONArray jsonArray = new JSONArray();   
  101.         for (T t : ts) {   
  102.             jsonArray.put(IObjectToJSON(t, includes));   
  103.         }   
  104.         return jsonArray;   
  105.     }   
  106.   
  107.     /**  
  108.      * 将对象数组封装成{@link JSONArray}对象,对象中的每个属性必须有<b>get</b>方法且符合<b>JavaBean</b>的命名标准。  
  109.      * 通过Annotation来封装JSONObject,JSONObject只包含带有{@link @Json}注释的属性  
  110.      * 通过设置jsonName来改变JSONObject的keyName  
  111.      *   
  112.      * @author (Jessdy) 编写日期:May 9, 2008  
  113.      *   
  114.      * @param <T>  
  115.      * @param ts  
  116.      *            需要转换成JSONArray的对象数组  
  117.      * @return  
  118.      */  
  119.     public static <T> JSONArray ArrayToJSONByAnnotation(T[] ts) {   
  120.         JSONArray jsonArray = new JSONArray();   
  121.         for (T t : ts) {   
  122.             jsonArray.put(ObjectToJSONByAnnotation(t));   
  123.         }   
  124.         return jsonArray;   
  125.     }   
  126.   
  127.     /**  
  128.      * 将对象队列封装成{@link JSONArray}对象,对象中的每个属性必须有<b>get</b>方法且符合<b>JavaBean</b>的命名标准。  
  129.      *   
  130.      * @author (Jessdy) 编写日期:May 9, 2008  
  131.      *   
  132.      * @param <T>  
  133.      * @param ts  
  134.      *            需要转换成JSONArray的对象队列  
  135.      * @return  
  136.      */  
  137.     public static <T> JSONArray ArrayToJSON(List<T> ts) {   
  138.         JSONArray jsonArray = new JSONArray();   
  139.         for (T t : ts) {   
  140.             jsonArray.put(ObjectToJSON(t));   
  141.         }   
  142.         return jsonArray;   
  143.     }   
  144.        
  145.     /**  
  146.      * 将对象队列封装成{@link JSONArray}对象,对象中的每个属性必须有<b>get</b>方法且符合<b>JavaBean</b>的命名标准。  
  147.      *   
  148.      * @author (Jessdy) 编写日期:May 9, 2008  
  149.      *   
  150.      * @param <T>  
  151.      * @param ts  
  152.      *            需要转换成JSONArray的对象队列  
  153.      * @param filters  
  154.      *            被过滤的属性字符数组  
  155.      * @return  
  156.      */  
  157.     public static <T> JSONArray ArrayToJSON(List<T> ts, String[] filters) {   
  158.         JSONArray jsonArray = new JSONArray();   
  159.         for (T t : ts) {   
  160.             jsonArray.put(ObjectToJSON(t, filters));   
  161.         }   
  162.         return jsonArray;   
  163.     }   
  164.        
  165.     /**  
  166.      * 将对象队列封装成{@link JSONArray}对象,对象中的每个属性必须有<b>get</b>方法且符合<b>JavaBean</b>的命名标准。  
  167.      *   
  168.      * @author (Jessdy)  
  169.      * 编写日期:Jul 23, 2008  
  170.      *   
  171.      * @param <T>  
  172.      * @param ts 需要转换成JSONArray的对象队列  
  173.      * @param includes 被包含的属性字符数组  
  174.      * @return  
  175.      */  
  176.     public static <T> JSONArray IArrayToJSON(List<T> ts, String[] includes) {   
  177.         JSONArray jsonArray = new JSONArray();   
  178.         for (T t : ts) {   
  179.             jsonArray.put(IObjectToJSON(t, includes));   
  180.         }   
  181.         return jsonArray;   
  182.     }   
  183.        
  184.     /**  
  185.      * 将对象队列封装成{@link JSONArray}对象,对象中的每个属性必须有<b>get</b>方法且符合<b>JavaBean</b>的命名标准。  
  186.      * 通过Annotation来封装JSONObject,JSONObject只包含带有{@link @Json}注释的属性  
  187.      * 通过设置jsonName来改变JSONObject的keyName  
  188.      *   
  189.      * @author (Jessdy) 编写日期:May 9, 2008  
  190.      *   
  191.      * @param <T>  
  192.      * @param ts  
  193.      *            需要转换成JSONArray的对象队列  
  194.      * @return  
  195.      */  
  196.     public static <T> JSONArray ArrayToJSONByAnnotation(List<T> ts) {   
  197.         JSONArray jsonArray = new JSONArray();   
  198.         for (T t : ts) {   
  199.             jsonArray.put(ObjectToJSONByAnnotation(t));   
  200.         }   
  201.         return jsonArray;   
  202.     }   
  203.   
  204.     /**  
  205.      * 将Map集合封装成{@link JSONArray}对象,对象中的每个属性必须有<b>get</b>方法且符合<b>JavaBean</b>的命名标准。  
  206.      * 通过Annotation来封装JSONObject,JSONObject只包含带有{@link @Json}注释的属性  
  207.      * 通过设置jsonName来改变JSONObject的keyName  
  208.      * @author (Jessdy)  
  209.      * 编写日期:Jul 25, 2008  
  210.      *   
  211.      * @param <K> 键类型  
  212.      * @param <T> 值类型  
  213.      * @param ts 需要转换成JSONArray的Map  
  214.      * @return  
  215.      */  
  216.     public static <K, T> JSONArray MapToJSONByAnnotation(Map<K, T> ts) {   
  217.         JSONArray jsonArray = new JSONArray();   
  218.         Iterator<K> keys = ts.keySet().iterator();   
  219.         while (keys.hasNext()) {   
  220.             K key = keys.next();   
  221.             jsonArray.put(ObjectToJSONByAnnotation(ts.get(key)));   
  222.         }   
  223.         return jsonArray;   
  224.     }   
  225.        
  226.     /**  
  227.      *   
  228.      * @author (Jessdy)  
  229.      * 编写日期:Jul 25, 2008  
  230.      *   
  231.      * @param <K>  
  232.      * @param <T>  
  233.      * @param ts  
  234.      * @return  
  235.      */  
  236.     public static <K, T> JSONArray MapToJSON(Map<K, T> ts, String[] filters) {   
  237.         JSONArray jsonArray = new JSONArray();   
  238.         Iterator<K> keys = ts.keySet().iterator();   
  239.         while (keys.hasNext()) {   
  240.             K key = keys.next();   
  241.             jsonArray.put(ObjectToJSON(ts.get(key), filters));   
  242.         }   
  243.         return jsonArray;   
  244.     }   
  245.   
  246.     /**  
  247.      *   
  248.      * @author (Jessdy)  
  249.      * 编写日期:Jul 25, 2008  
  250.      *   
  251.      * @param <K>  
  252.      * @param <T>  
  253.      * @param ts  
  254.      * @return  
  255.      */  
  256.     public static <K, T> JSONArray IMapToJSON(Map<K, T> ts, String[] includes) {   
  257.         JSONArray jsonArray = new JSONArray();   
  258.         Iterator<K> keys = ts.keySet().iterator();   
  259.         while (keys.hasNext()) {   
  260.             K key = keys.next();   
  261.             jsonArray.put(IObjectToJSON(ts.get(key), includes));   
  262.         }   
  263.         return jsonArray;   
  264.     }  
posted @ 2009-01-08 20:52  猪鼻驴耳  阅读(2240)  评论(3)    收藏  举报