Android轻量级JSON序列化和反序列化


最近开发一直使用JSON数据传输,网络中流程的JSON解析导入包太多了,在网上找了下,结合自己改编,简单实现JSON解析,支持集合和对象泛化。 [java]
  1. package com.callgetway.util;  
  2.   
  3. import java.lang.reflect.Array;  
  4. import java.lang.reflect.Field;  
  5. import java.lang.reflect.Method;  
  6. import java.lang.reflect.ParameterizedType;  
  7. import java.lang.reflect.Type;  
  8. import java.text.SimpleDateFormat;  
  9. import java.util.Collection;  
  10. import java.util.Date;  
  11. import java.util.HashMap;  
  12. import java.util.Iterator;  
  13. import java.util.List;  
  14. import java.util.Locale;  
  15. import java.util.Map;  
  16.   
  17. import org.json.JSONArray;  
  18. import org.json.JSONException;  
  19. import org.json.JSONObject;  
  20. import org.json.JSONStringer;  
  21.   
  22. import Android.util.Log;  
  23.   
  24.   
  25. /** 
  26.  * @author keane 
  27.  * @version 1.0 
  28.  * 
  29.  */  
  30. public class JSONHelper {  
  31.   
  32.     private static String TAG = "JSONHelper";  
  33.   
  34.     /** 
  35.      * 将对象转换成Json字符串 
  36.      * @param obj 
  37.      * @return 
  38.      */  
  39.     public static String toJSON(Object obj) {  
  40.         JSONStringer js = new JSONStringer();  
  41.         serialize(js, obj);  
  42.         Log.d(TAG, "JSONHelper toJSON  :" + js.toString());  
  43.         return js.toString();  
  44.     }  
  45.   
  46.     /** 
  47.      * 序列化为JSON 
  48.      * @param js 
  49.      * @param o 
  50.      */  
  51.     private static void serialize(JSONStringer js, Object o) {  
  52.         if (isNull(o)) {  
  53.             try {  
  54.                 js.value(null);  
  55.             } catch (JSONException e) {  
  56.                 e.printStackTrace();  
  57.             }  
  58.             return;  
  59.         }  
  60.   
  61.         Class<?> clazz = o.getClass();  
  62.         if (isObject(clazz)) { // 对象   
  63.             serializeObject(js, o);  
  64.         } else if (isArray(clazz)) { // 数组   
  65.             serializeArray(js, o);  
  66.         } else if (isCollection(clazz)) { // 集合   
  67.             Collection<?> collection = (Collection<?>) o;  
  68.             serializeCollect(js, collection);  
  69.         } else { // 单个值   
  70.             try {  
  71.                 js.value(o);  
  72.             } catch (JSONException e) {  
  73.                 e.printStackTrace();  
  74.             }  
  75.         }  
  76.     }  
  77.   
  78.     /** 
  79.      * 序列化数组  
  80.      * @param js 
  81.      * @param array 
  82.      */  
  83.     private static void serializeArray(JSONStringer js, Object array) {  
  84.         try {  
  85.             js.array();  
  86.             for (int i = 0; i < Array.getLength(array); ++i) {  
  87.                 Object o = Array.get(array, i);  
  88.                 serialize(js, o);  
  89.             }  
  90.             js.endArray();  
  91.         } catch (Exception e) {  
  92.             e.printStackTrace();  
  93.         }  
  94.     }  
  95.   
  96.     /** 
  97.      * 序列化集合 
  98.      * @param js 
  99.      * @param collection 
  100.      */  
  101.     private static void serializeCollect(JSONStringer js, Collection<?> collection) {  
  102.         try {  
  103.             js.array();  
  104.             for (Object o : collection) {  
  105.                 serialize(js, o);  
  106.             }  
  107.             js.endArray();  
  108.         } catch (Exception e) {  
  109.             e.printStackTrace();  
  110.         }  
  111.     }  
  112.   
  113.     /** 
  114.      * 序列化对象 
  115.      * @param js 
  116.      * @param obj 
  117.      */  
  118.     private static void serializeObject(JSONStringer js, Object obj) {  
  119.         try {  
  120.             js.object();  
  121.             Class<? extends Object> objClazz = obj.getClass();  
  122.             Method[] methods = objClazz.getDeclaredMethods();     
  123.             Field[] fields = objClazz.getDeclaredFields();       
  124.             for (Field field : fields) {     
  125.                 try {     
  126.                     String fieldType = field.getType().getSimpleName();     
  127.                     String fieldGetName = parseMethodName(field.getName(),"get");     
  128.                     if (!haveMethod(methods, fieldGetName)) {     
  129.                         continue;     
  130.                     }     
  131.                     Method fieldGetMet = objClazz.getMethod(fieldGetName, new Class[] {});     
  132.                     Object fieldVal = fieldGetMet.invoke(obj, new Object[] {});     
  133.                     String result = null;     
  134.                     if ("Date".equals(fieldType)) {     
  135.                         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",     
  136.                                 Locale.US);     
  137.                         result = sdf.format((Date)fieldVal);    
  138.   
  139.                     } else {     
  140.                         if (null != fieldVal) {     
  141.                             result = String.valueOf(fieldVal);     
  142.                         }     
  143.                     }     
  144.                     js.key(field.getName());  
  145.                     serialize(js, result);    
  146.                 } catch (Exception e) {     
  147.                     continue;     
  148.                 }     
  149.             }    
  150.             js.endObject();  
  151.         } catch (Exception e) {  
  152.             e.printStackTrace();  
  153.         }  
  154.     }  
  155.   
  156.     /** 
  157.      * 判断是否存在某属性的 get方法 
  158.      *  
  159.      * @param methods 
  160.      * @param fieldGetMet 
  161.      * @return boolean 
  162.      */  
  163.     public static boolean haveMethod(Method[] methods, String fieldMethod) {  
  164.         for (Method met : methods) {  
  165.             if (fieldMethod.equals(met.getName())) {  
  166.                 return true;  
  167.             }  
  168.         }  
  169.         return false;  
  170.     }  
  171.   
  172.     /** 
  173.      * 拼接某属性的 get或者set方法 
  174.      * @param fieldName 
  175.      * @param methodType 
  176.      * @return 
  177.      */  
  178.     public static String parseMethodName(String fieldName,String methodType) {  
  179.         if (null == fieldName || "".equals(fieldName)) {  
  180.             return null;  
  181.         }  
  182.         return methodType + fieldName.substring(01).toUpperCase()  
  183.                 + fieldName.substring(1);  
  184.     }  
  185.   
  186.   
  187.       
  188.     /**   
  189.      * set属性的值到Bean   
  190.      * @param obj   
  191.      * @param valMap   
  192.      */    
  193.     public static void setFieldValue(Object obj, Map<String, String> valMap) {     
  194.         Class<?> cls = obj.getClass();     
  195.         // 取出bean里的所有方法      
  196.         Method[] methods = cls.getDeclaredMethods();     
  197.         Field[] fields = cls.getDeclaredFields();     
  198.     
  199.         for (Field field : fields) {     
  200.             try {       
  201.                 String setMetodName = parseMethodName(field.getName(),"set");     
  202.                 if (!haveMethod(methods, setMetodName)) {     
  203.                     continue;     
  204.                 }     
  205.                 Method fieldMethod = cls.getMethod(setMetodName, field     
  206.                         .getType());     
  207.                 String value = valMap.get(field.getName());     
  208.                 if (null != value && !"".equals(value)) {     
  209.                     String fieldType = field.getType().getSimpleName();     
  210.                     if ("String".equals(fieldType)) {     
  211.                         fieldMethod.invoke(obj, value);     
  212.                     } else if ("Date".equals(fieldType)) {     
  213.                         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.US);     
  214.                         Date temp = sdf.parse(value);      
  215.                         fieldMethod.invoke(obj, temp);     
  216.                     } else if ("Integer".equals(fieldType)     
  217.                             || "int".equals(fieldType)) {     
  218.                         Integer intval = Integer.parseInt(value);     
  219.                         fieldMethod.invoke(obj, intval);     
  220.                     } else if ("Long".equalsIgnoreCase(fieldType)) {     
  221.                         Long temp = Long.parseLong(value);     
  222.                         fieldMethod.invoke(obj, temp);     
  223.                     } else if ("Double".equalsIgnoreCase(fieldType)) {     
  224.                         Double temp = Double.parseDouble(value);     
  225.                         fieldMethod.invoke(obj, temp);     
  226.                     } else if ("Boolean".equalsIgnoreCase(fieldType)) {     
  227.                         Boolean temp = Boolean.parseBoolean(value);     
  228.                         fieldMethod.invoke(obj, temp);     
  229.                     } else {     
  230.                         System.out.println("setFieldValue not supper type:" + fieldType);     
  231.                     }     
  232.                 }     
  233.             } catch (Exception e) {     
  234.                 continue;     
  235.             }     
  236.         }     
  237.     
  238.     }     
  239.       
  240.     /** 
  241.      * 对象转Map 
  242.      * @param obj 
  243.      * @return 
  244.      */  
  245.     public static Map<String, String> getFieldValueMap(Object obj) {     
  246.         Class<?> cls = obj.getClass();     
  247.         Map<String, String> valueMap = new HashMap<String, String>();     
  248.         // 取出bean里的所有方法      
  249.         Method[] methods = cls.getDeclaredMethods();     
  250.         Field[] fields = cls.getDeclaredFields();       
  251.         for (Field field : fields) {     
  252.             try {     
  253.                 String fieldType = field.getType().getSimpleName();     
  254.                 String fieldGetName = parseMethodName(field.getName(),"get");     
  255.                 if (!haveMethod(methods, fieldGetName)) {     
  256.                     continue;     
  257.                 }     
  258.                 Method fieldGetMet = cls.getMethod(fieldGetName, new Class[] {});     
  259.                 Object fieldVal = fieldGetMet.invoke(obj, new Object[] {});     
  260.                 String result = null;     
  261.                 if ("Date".equals(fieldType)) {     
  262.                     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.CHINA);     
  263.                     result = sdf.format((Date)fieldVal);     
  264.   
  265.                 } else {     
  266.                     if (null != fieldVal) {     
  267.                         result = String.valueOf(fieldVal);     
  268.                     }     
  269.                 }     
  270.                 valueMap.put(field.getName(), result);     
  271.             } catch (Exception e) {     
  272.                 continue;     
  273.             }     
  274.         }     
  275.         return valueMap;     
  276.     
  277.     }     
  278.     
  279.   
  280.   
  281.     /** 
  282.      * 给对象的字段赋值 
  283.      * @param obj 
  284.      * @param fieldSetMethod 
  285.      * @param fieldType 
  286.      * @param value 
  287.      */  
  288.     public static void setFiedlValue(Object obj,Method fieldSetMethod,String fieldType,Object value){  
  289.              
  290.         try {      
  291.             if (null != value && !"".equals(value)) {      
  292.                 if ("String".equals(fieldType)) {     
  293.                     fieldSetMethod.invoke(obj, value.toString());     
  294.                 } else if ("Date".equals(fieldType)) {     
  295.                     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.CHINA);     
  296.                     Date temp = sdf.parse(value.toString());      
  297.                     fieldSetMethod.invoke(obj, temp);     
  298.                 } else if ("Integer".equals(fieldType)     
  299.                         || "int".equals(fieldType)) {     
  300.                     Integer intval = Integer.parseInt(value.toString());     
  301.                     fieldSetMethod.invoke(obj, intval);     
  302.                 } else if ("Long".equalsIgnoreCase(fieldType)) {     
  303.                     Long temp = Long.parseLong(value.toString());     
  304.                     fieldSetMethod.invoke(obj, temp);     
  305.                 } else if ("Double".equalsIgnoreCase(fieldType)) {     
  306.                     Double temp = Double.parseDouble(value.toString());     
  307.                     fieldSetMethod.invoke(obj, temp);     
  308.                 } else if ("Boolean".equalsIgnoreCase(fieldType)) {     
  309.                     Boolean temp = Boolean.parseBoolean(value.toString());     
  310.                     fieldSetMethod.invoke(obj, temp);     
  311.                 } else {     
  312.                     fieldSetMethod.invoke(obj, value);   
  313.                     Log.e(TAG, TAG  + ">>>>setFiedlValue -> not supper type" + fieldType);     
  314.                 }   
  315.             }  
  316.                   
  317.         } catch (Exception e) {     
  318.             Log.e(TAG, TAG  + ">>>>>>>>>>set value error.",e);  
  319.         }     
  320.       
  321.     }  
  322.       
  323.   
  324.     /** 
  325.      * 反序列化简单对象 
  326.      * @param jo 
  327.      * @param clazz 
  328.      * @return 
  329.      */  
  330.     public static <T> T parseObject(JSONObject jo, Class<T> clazz) {  
  331.         if (clazz == null || isNull(jo)) {  
  332.             return null;  
  333.         }  
  334.   
  335.         T obj = newInstance(clazz);  
  336.         if (obj == null) {  
  337.             return null;  
  338.         }  
  339.         if(isMap(clazz)){   
  340.             setField(obj,jo);  
  341.         }else{  
  342.               // 取出bean里的所有方法      
  343.             Method[] methods = clazz.getDeclaredMethods();     
  344.             Field[] fields = clazz.getDeclaredFields();               
  345.             for (Field f : fields) {  
  346.                 String setMetodName = parseMethodName(f.getName(),"set");     
  347.                 if (!haveMethod(methods, setMetodName)) {     
  348.                     continue;     
  349.                 }                   
  350.                 try {  
  351.                     Method fieldMethod = clazz.getMethod(setMetodName, f.getType());  
  352.                     setField(obj,fieldMethod,f, jo);  
  353.                 } catch (Exception e) {  
  354.                     e.printStackTrace();  
  355.                 }    
  356.             }  
  357.         }  
  358.         return obj;  
  359.     }  
  360.   
  361.       
  362.     /** 
  363.      * 反序列化简单对象 
  364.      * @param jsonString 
  365.      * @param clazz 
  366.      * @return 
  367.      */  
  368.     public static <T> T parseObject(String jsonString, Class<T> clazz) {  
  369.         if (clazz == null || jsonString == null || jsonString.length() == 0) {  
  370.             return null;  
  371.         }  
  372.           
  373.         JSONObject jo = null;  
  374.         try {  
  375.             jo = new JSONObject(jsonString);  
  376.         } catch (JSONException e) {  
  377.             e.printStackTrace();  
  378.         }  
  379.   
  380.         if (isNull(jo)) {  
  381.             return null;  
  382.         }  
  383.   
  384.         return parseObject(jo, clazz);  
  385.     }  
  386.   
  387.     /** 
  388.      * 反序列化数组对象 
  389.      * @param ja 
  390.      * @param clazz 
  391.      * @return 
  392.      */  
  393.     public static <T> T[] parseArray(JSONArray ja, Class<T> clazz) {  
  394.         if (clazz == null || isNull(ja)) {  
  395.             return null;  
  396.         }  
  397.   
  398.         int len = ja.length();  
  399.   
  400.         @SuppressWarnings("unchecked")  
  401.         T[] array = (T[]) Array.newInstance(clazz, len);  
  402.   
  403.         for (int i = 0; i < len; ++i) {  
  404.             try {  
  405.                 JSONObject jo = ja.getJSONObject(i);  
  406.                 T o = parseObject(jo, clazz);  
  407.                 array[i] = o;  
  408.             } catch (JSONException e) {  
  409.                 e.printStackTrace();  
  410.             }  
  411.         }  
  412.   
  413.         return array;  
  414.     }  
  415.   
  416.       
  417.     /** 
  418.      * 反序列化数组对象 
  419.      * @param jsonString 
  420.      * @param clazz 
  421.      * @return 
  422.      */  
  423.     public static <T> T[] parseArray(String jsonString, Class<T> clazz) {  
  424.         if (clazz == null || jsonString == null || jsonString.length() == 0) {  
  425.             return null;  
  426.         }  
  427.         JSONArray jo = null;  
  428.         try {  
  429.             jo = new JSONArray(jsonString);  
  430.         } catch (JSONException e) {  
  431.             e.printStackTrace();  
  432.         }  
  433.   
  434.         if (isNull(jo)) {  
  435.             return null;  
  436.         }  
  437.   
  438.         return parseArray(jo, clazz);  
  439.     }  
  440.   
  441.     /** 
  442.      * 反序列化泛型集合 
  443.      * @param ja 
  444.      * @param collectionClazz 
  445.      * @param genericType 
  446.      * @return 
  447.      */  
  448.     @SuppressWarnings("unchecked")  
  449.     public static <T> Collection<T> parseCollection(JSONArray ja, Class<?> collectionClazz,  
  450.             Class<T> genericType) {  
  451.   
  452.         if (collectionClazz == null || genericType == null || isNull(ja)) {  
  453.             return null;  
  454.         }  
  455.   
  456.         Collection<T> collection = (Collection<T>) newInstance(collectionClazz);  
  457.   
  458.         for (int i = 0; i < ja.length(); ++i) {  
  459.             try {  
  460.                 JSONObject jo = ja.getJSONObject(i);  
  461.                 T o = parseObject(jo, genericType);  
  462.                 collection.add(o);  
  463.             } catch (JSONException e) {  
  464.                 e.printStackTrace();  
  465.             }  
  466.         }  
  467.   
  468.         return collection;  
  469.     }  
  470.   
  471.     /** 
  472.      * 反序列化泛型集合 
  473.      * @param jsonString 
  474.      * @param collectionClazz 
  475.      * @param genericType 
  476.      * @return 
  477.      */  
  478.     public static <T> Collection<T> parseCollection(String jsonString, Class<?> collectionClazz,  
  479.             Class<T> genericType) {  
  480.         if (collectionClazz == null || genericType == null || jsonString == null  
  481.                 || jsonString.length() == 0) {  
  482.             return null;  
  483.         }  
  484.         JSONArray jo = null;  
  485.         try {  
  486.             jo = new JSONArray(jsonString);  
  487.         } catch (JSONException e) {  
  488.             e.printStackTrace();  
  489.         }  
  490.   
  491.         if (isNull(jo)) {  
  492.             return null;  
  493.         }  
  494.   
  495.         return parseCollection(jo, collectionClazz, genericType);  
  496.     }  
  497.   
  498.     /** 
  499.      * 根据类型创建对象 
  500.      * @param clazz 
  501.      * @return 
  502.      */  
  503.     private static <T> T newInstance(Class<T> clazz) {  
  504.         if (clazz == null)  
  505.             return null;  
  506.         T obj = null;  
  507.         try {  
  508.             obj = clazz.newInstance();  
  509.         } catch (Exception e) {  
  510.             e.printStackTrace();  
  511.         }  
  512.         return obj;  
  513.     }  
  514.       
  515.     /** 
  516.      * 设定Map的值 
  517.      * @param obj 
  518.      * @param jo 
  519.      */  
  520.     private static void setField(Object obj, JSONObject jo) {  
  521.         try {  
  522.             @SuppressWarnings("unchecked")  
  523.             Iterator<String> keyIter = jo.keys();  
  524.             String key;  
  525.             Object value;  
  526.             @SuppressWarnings("unchecked")  
  527.             Map<String, Object> valueMap = (Map<String, Object>) obj;  
  528.             while (keyIter.hasNext()) {  
  529.                 key = (String) keyIter.next();  
  530.                 value = jo.get(key);                  
  531.                 valueMap.put(key, value);  
  532.   
  533.             }  
  534.         } catch (JSONException e) {  
  535.             e.printStackTrace();  
  536.         }  
  537.     }  
  538.       
  539.       
  540.     /** 
  541.      * 设定字段的值 
  542.      * @param obj 
  543.      * @param fieldSetMethod 
  544.      * @param f 
  545.      * @param jo 
  546.      */  
  547.     private static void setField(Object obj, Method fieldSetMethod,Field f, JSONObject jo) {  
  548.         String name = f.getName();  
  549.         Class<?> clazz = f.getType();       
  550.         try {  
  551.             if (isArray(clazz)) { // 数组   
  552.                 Class<?> c = clazz.getComponentType();  
  553.                 JSONArray ja = jo.optJSONArray(name);  
  554.                 if (!isNull(ja)) {  
  555.                     Object array = parseArray(ja, c);  
  556.                     setFiedlValue(obj, fieldSetMethod, clazz.getSimpleName(), array);  
  557.                 }  
  558.             } else if (isCollection(clazz)) { // 泛型集合   
  559.                 // 获取定义的泛型类型   
  560.                 Class<?> c = null;  
  561.                 Type gType = f.getGenericType();  
  562.                 if (gType instanceof ParameterizedType) {  
  563.                     ParameterizedType ptype = (ParameterizedType) gType;  
  564.                     Type[] targs = ptype.getActualTypeArguments();  
  565.                     if (targs != null && targs.length > 0) {  
  566.                         Type t = targs[0];  
  567.                         c = (Class<?>) t;  
  568.                     }  
  569.                 }  
  570.   
  571.                 JSONArray ja = jo.optJSONArray(name);  
  572.                 if (!isNull(ja)) {  
  573.                     Object o = parseCollection(ja, clazz, c);  
  574.                     setFiedlValue(obj, fieldSetMethod, clazz.getSimpleName(), o);  
  575.                 }  
  576.             } else if (isSingle(clazz)) { // 值类型   
  577.                 Object o = jo.opt(name);  
  578.                 if (o != null) {  
  579.                     setFiedlValue(obj, fieldSetMethod, clazz.getSimpleName(), o);  
  580.                 }  
  581.             } else if (isObject(clazz)) { // 对象   
  582.                 JSONObject j = jo.optJSONObject(name);  
  583.                 if (!isNull(j)) {  
  584.                     Object o = parseObject(j, clazz);  
  585.                     setFiedlValue(obj, fieldSetMethod, clazz.getSimpleName(), o);  
  586.                 }  
  587.             } else if (isList(clazz)) { // 列表   
  588. //              JSONObject j = jo.optJSONObject(name);   
  589. //              if (!isNull(j)) {   
  590. //                  Object o = parseObject(j, clazz);   
  591. //                  f.set(obj, o);   
  592. //              }   
  593.             } else {  
  594.                 throw new Exception("unknow type!");  
  595.             }  
  596.         } catch (Exception e) {  
  597.             e.printStackTrace();  
  598.         }  
  599.     }  
  600.       
  601.     /** 
  602.      * 设定字段的值  
  603.      * @param obj 
  604.      * @param f 
  605.      * @param jo 
  606.      */  
  607.     private static void setField(Object obj, Field f, JSONObject jo) {  
  608.         String name = f.getName();  
  609.         Class<?> clazz = f.getType();  
  610.         try {  
  611.             if (isArray(clazz)) { // 数组   
  612.                 Class<?> c = clazz.getComponentType();  
  613.                 JSONArray ja = jo.optJSONArray(name);  
  614.                 if (!isNull(ja)) {  
  615.                     Object array = parseArray(ja, c);  
  616.                     f.set(obj, array);  
  617.                 }  
  618.             } else if (isCollection(clazz)) { // 泛型集合   
  619.                 // 获取定义的泛型类型   
  620.                 Class<?> c = null;  
  621.                 Type gType = f.getGenericType();  
  622.                 if (gType instanceof ParameterizedType) {  
  623.                     ParameterizedType ptype = (ParameterizedType) gType;  
  624.                     Type[] targs = ptype.getActualTypeArguments();  
  625.                     if (targs != null && targs.length > 0) {  
  626.                         Type t = targs[0];  
  627.                         c = (Class<?>) t;  
  628.                     }  
  629.                 }  
  630.   
  631.                 JSONArray ja = jo.optJSONArray(name);  
  632.                 if (!isNull(ja)) {  
  633.                     Object o = parseCollection(ja, clazz, c);  
  634.                     f.set(obj, o);  
  635.                 }  
  636.             } else if (isSingle(clazz)) { // 值类型   
  637.                 Object o = jo.opt(name);  
  638.                 if (o != null) {  
  639.                     f.set(obj, o);  
  640.                 }  
  641.             } else if (isObject(clazz)) { // 对象   
  642.                 JSONObject j = jo.optJSONObject(name);  
  643.                 if (!isNull(j)) {  
  644.                     Object o = parseObject(j, clazz);  
  645.                     f.set(obj, o);  
  646.                 }  
  647.             } else if (isList(clazz)) { // 列表   
  648.                 JSONObject j = jo.optJSONObject(name);  
  649.                 if (!isNull(j)) {  
  650.                     Object o = parseObject(j, clazz);  
  651.                     f.set(obj, o);  
  652.                 }  
  653.             }else {  
  654.                 throw new Exception("unknow type!");  
  655.             }  
  656.         } catch (Exception e) {  
  657.             e.printStackTrace();  
  658.         }  
  659.     }  
  660.   
  661.     /** 
  662.      * 判断对象是否为空 
  663.      * @param obj 
  664.      * @return 
  665.      */  
  666.     private static boolean isNull(Object obj) {  
  667.         if (obj instanceof JSONObject) {  
  668.             return JSONObject.NULL.equals(obj);  
  669.         }  
  670.         return obj == null;  
  671.     }  
  672.   
  673.     /** 
  674.      * 判断是否是值类型  
  675.      * @param clazz 
  676.      * @return 
  677.      */  
  678.     private static boolean isSingle(Class<?> clazz) {  
  679.         return isBoolean(clazz) || isNumber(clazz) || isString(clazz);  
  680.     }  
  681.   
  682.     /** 
  683.      * 是否布尔值 
  684.      * @param clazz 
  685.      * @return 
  686.      */  
  687.     public static boolean isBoolean(Class<?> clazz) {  
  688.         return (clazz != null)  
  689.                 && ((Boolean.TYPE.isAssignableFrom(clazz)) || (Boolean.class  
  690.                         .isAssignableFrom(clazz)));  
  691.     }  
  692.   
  693.     /** 
  694.      * 是否数值  
  695.      * @param clazz 
  696.      * @return 
  697.      */  
  698.     public static boolean isNumber(Class<?> clazz) {  
  699.         return (clazz != null)  
  700.                 && ((Byte.TYPE.isAssignableFrom(clazz)) || (Short.TYPE.isAssignableFrom(clazz))  
  701.                         || (Integer.TYPE.isAssignableFrom(clazz))  
  702.                         || (Long.TYPE.isAssignableFrom(clazz))  
  703.                         || (Float.TYPE.isAssignableFrom(clazz))  
  704.                         || (Double.TYPE.isAssignableFrom(clazz)) || (Number.class  
  705.                         .isAssignableFrom(clazz)));  
  706.     }  
  707.   
  708.     /** 
  709.      * 判断是否是字符串  
  710.      * @param clazz 
  711.      * @return 
  712.      */  
  713.     public static boolean isString(Class<?> clazz) {  
  714.         return (clazz != null)  
  715.                 && ((String.class.isAssignableFrom(clazz))  
  716.                         || (Character.TYPE.isAssignableFrom(clazz)) || (Character.class  
  717.                         .isAssignableFrom(clazz)));  
  718.     }  
  719.   
  720.     /** 
  721.      * 判断是否是对象 
  722.      * @param clazz 
  723.      * @return 
  724.      */  
  725.     private static boolean isObject(Class<?> clazz) {  
  726.         return clazz != null && !isSingle(clazz) && !isArray(clazz) && !isCollection(clazz);  
  727.     }  
  728.   
  729.     /** 
  730.      * 判断是否是数组  
  731.      * @param clazz 
  732.      * @return 
  733.      */  
  734.     public static boolean isArray(Class<?> clazz) {  
  735.         return clazz != null && clazz.isArray();  
  736.     }  
  737.   
  738.     /** 
  739.      * 判断是否是集合 
  740.      * @param clazz 
  741.      * @return 
  742.      */  
  743.     public static boolean isCollection(Class<?> clazz) {  
  744.         return clazz != null && Collection.class.isAssignableFrom(clazz);  
  745.     }  
  746.           
  747.     /** 
  748.      * 判断是否是Map 
  749.      * @param clazz 
  750.      * @return 
  751.      */  
  752.     public static boolean isMap(Class<?> clazz) {  
  753.         return clazz != null && Map.class.isAssignableFrom(clazz);  
  754.     }  
  755.       
  756.     /** 
  757.      * 判断是否是列表  
  758.      * @param clazz 
  759.      * @return 
  760.      */  
  761.     public static boolean isList(Class<?> clazz) {  
  762.         return clazz != null && List.class.isAssignableFrom(clazz);  
  763.     }  
  764.       
  765.       
  766. }  

测试代码:

[java]
  1. public class User{  
  2.     private String name;  
  3.     private String password;  
  4.     public String getName() {  
  5.         return name;  
  6.     }  
  7.     public void setName(String name) {  
  8.         this.name = name;  
  9.     }  
  10.     public String getPassword() {  
  11.         return password;  
  12.     }  
  13.     public void setPassword(String password) {  
  14.         this.password = password;  
  15.     }  
  16.       
  17. }  
  18.   
  19. void testObj(){  
  20.     User user = new User();  
  21.     user.setName("abcd");  
  22.     user.setPassword("123456");  
  23.     String jsonStrUser = JSONHelper.toJSON(user);  
  24.     User jsonUser = JSONHelper.parseObject(jsonStrUser, User.class);          
  25.     Map mapUser = JSONHelper.parseObject(jsonStrUser, HashMap.class);  
  26. }  

相关内容