`

ANDROID轻量级JSON序列化和反序列化[转]

 
阅读更多

ANDROID JSON解析工具类,不需要第三方包,支持集合,直接贴代码。

 

[java] view plaincopy
  1. import java.lang.reflect.Array;  
  2. import java.lang.reflect.Field;  
  3. import java.lang.reflect.Method;  
  4. import java.lang.reflect.ParameterizedType;  
  5. import java.lang.reflect.Type;  
  6. import java.text.SimpleDateFormat;  
  7. import java.util.ArrayList;  
  8. import java.util.Collection;  
  9. import java.util.Date;  
  10. import java.util.HashMap;  
  11. import java.util.HashSet;  
  12. import java.util.Iterator;  
  13. import java.util.List;  
  14. import java.util.Locale;  
  15. import java.util.Map;  
  16. import java.util.Set;  
  17.   
  18. import org.json.JSONArray;  
  19. import org.json.JSONException;  
  20. import org.json.JSONObject;  
  21. import org.json.JSONStringer;  
  22.   
  23. import android.util.Log;  
  24.   
  25.   
  26. /** 
  27.  * @author keane 
  28.  * @version 1.0 
  29.  * 
  30.  */  
  31. public class JSONHelper {  
  32.   
  33.     private static String TAG = "JSONHelper";  
  34.   
  35.     /** 
  36.      * 将对象转换成Json字符串 
  37.      * @param obj 
  38.      * @return 
  39.      */  
  40.     public static String toJSON(Object obj) {  
  41.         JSONStringer js = new JSONStringer();  
  42.         serialize(js, obj);  
  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.      * @throws JSONException  
  330.      */  
  331.     public static <T> T parseObject(JSONObject jo, Class<T> clazz) throws JSONException {  
  332.         if (clazz == null || isNull(jo)) {  
  333.             return null;  
  334.         }  
  335.   
  336.         T obj = newInstance(clazz);  
  337.         if (obj == null) {  
  338.             return null;  
  339.         }  
  340.         if(isMap(clazz)){   
  341.             setField(obj,jo);  
  342.         }else{  
  343.               // 取出bean里的所有方法     
  344.             Method[] methods = clazz.getDeclaredMethods();     
  345.             Field[] fields = clazz.getDeclaredFields();               
  346.             for (Field f : fields) {  
  347.                 String setMetodName = parseMethodName(f.getName(),"set");     
  348.                 if (!haveMethod(methods, setMetodName)) {     
  349.                     continue;     
  350.                 }                   
  351.                 try {  
  352.                     Method fieldMethod = clazz.getMethod(setMetodName, f.getType());  
  353.                     setField(obj,fieldMethod,f, jo);  
  354.                 } catch (Exception e) {  
  355.                     e.printStackTrace();  
  356.                 }    
  357.             }  
  358.         }  
  359.         return obj;  
  360.     }  
  361.   
  362.       
  363.     /** 
  364.      * 反序列化简单对象 
  365.      * @param jsonString 
  366.      * @param clazz 
  367.      * @return 
  368.      * @throws JSONException  
  369.      */  
  370.     public static <T> T parseObject(String jsonString, Class<T> clazz) throws JSONException {  
  371.         if (clazz == null || jsonString == null || jsonString.length() == 0) {  
  372.             return null;  
  373.         }  
  374.           
  375.         JSONObject jo = null;  
  376.         jo = new JSONObject(jsonString);  
  377.         if (isNull(jo)) {  
  378.             return null;  
  379.         }  
  380.   
  381.         return parseObject(jo, clazz);  
  382.     }  
  383.   
  384.     /** 
  385.      * 反序列化数组对象 
  386.      * @param ja 
  387.      * @param clazz 
  388.      * @return 
  389.      */  
  390.     public static <T> T[] parseArray(JSONArray ja, Class<T> clazz) {  
  391.         if (clazz == null || isNull(ja)) {  
  392.             return null;  
  393.         }  
  394.   
  395.         int len = ja.length();  
  396.   
  397.         @SuppressWarnings("unchecked")  
  398.         T[] array = (T[]) Array.newInstance(clazz, len);  
  399.   
  400.         for (int i = 0; i < len; ++i) {  
  401.             try {  
  402.                 JSONObject jo = ja.getJSONObject(i);  
  403.                 T o = parseObject(jo, clazz);  
  404.                 array[i] = o;  
  405.             } catch (JSONException e) {  
  406.                 e.printStackTrace();  
  407.             }  
  408.         }  
  409.   
  410.         return array;  
  411.     }  
  412.   
  413.       
  414.     /** 
  415.      * 反序列化数组对象 
  416.      * @param jsonString 
  417.      * @param clazz 
  418.      * @return 
  419.      */  
  420.     public static <T> T[] parseArray(String jsonString, Class<T> clazz) {  
  421.         if (clazz == null || jsonString == null || jsonString.length() == 0) {  
  422.             return null;  
  423.         }  
  424.         JSONArray jo = null;  
  425.         try {  
  426.             jo = new JSONArray(jsonString);  
  427.         } catch (JSONException e) {  
  428.             e.printStackTrace();  
  429.         }  
  430.   
  431.         if (isNull(jo)) {  
  432.             return null;  
  433.         }  
  434.   
  435.         return parseArray(jo, clazz);  
  436.     }  
  437.   
  438.     /** 
  439.      * 反序列化泛型集合 
  440.      * @param ja 
  441.      * @param collectionClazz 
  442.      * @param genericType 
  443.      * @return 
  444.      * @throws JSONException  
  445.      */  
  446.     @SuppressWarnings("unchecked")  
  447.     public static <T> Collection<T> parseCollection(JSONArray ja, Class<?> collectionClazz,  
  448.             Class<T> genericType) throws JSONException {  
  449.   
  450.         if (collectionClazz == null || genericType == null || isNull(ja)) {  
  451.             return null;  
  452.         }  
  453.   
  454.         Collection<T> collection = (Collection<T>) newInstance(collectionClazz);  
  455.   
  456.         for (int i = 0; i < ja.length(); ++i) {  
  457.             try {  
  458.                 JSONObject jo = ja.getJSONObject(i);  
  459.                 T o = parseObject(jo, genericType);  
  460.                 collection.add(o);  
  461.             } catch (JSONException e) {  
  462.                 e.printStackTrace();  
  463.             }  
  464.         }  
  465.   
  466.         return collection;  
  467.     }  
  468.   
  469.     /** 
  470.      * 反序列化泛型集合 
  471.      * @param jsonString 
  472.      * @param collectionClazz 
  473.      * @param genericType 
  474.      * @return 
  475.      * @throws JSONException  
  476.      */  
  477.     public static <T> Collection<T> parseCollection(String jsonString, Class<?> collectionClazz,  
  478.             Class<T> genericType) throws JSONException {  
  479.         if (collectionClazz == null || genericType == null || jsonString == null  
  480.                 || jsonString.length() == 0) {  
  481.             return null;  
  482.         }  
  483.         JSONArray jo = null;  
  484.         try {  
  485.             jo = new JSONArray(jsonString);  
  486.         } catch (JSONException e) {  
  487.             e.printStackTrace();  
  488.         }  
  489.   
  490.         if (isNull(jo)) {  
  491.             return null;  
  492.         }  
  493.   
  494.         return parseCollection(jo, collectionClazz, genericType);  
  495.     }  
  496.   
  497.     /** 
  498.      * 根据类型创建对象 
  499.      * @param clazz 
  500.      * @return 
  501.      * @throws JSONException  
  502.      */  
  503.     private static <T> T newInstance(Class<T> clazz) throws JSONException {  
  504.         if (clazz == null)  
  505.             return null;  
  506.         T obj = null;  
  507.         if (clazz.isInterface()) {  
  508.             if (clazz.equals(Map.class)) {  
  509.                 obj = (T) new HashMap();  
  510.             }else if (clazz.equals(List.class)) {  
  511.                 obj = (T) new ArrayList();  
  512.             }else if (clazz.equals(Set.class)) {  
  513.                 obj = (T) new HashSet();  
  514.             }else{  
  515.                 throw new JSONException("unknown interface: " + clazz);  
  516.             }  
  517.         }else{  
  518.             try {  
  519.                 obj = clazz.newInstance();  
  520.             }catch (Exception e) {  
  521.                 throw new JSONException("unknown class type: " + clazz);  
  522.             }  
  523.         }     
  524.         return obj;  
  525.     }  
  526.       
  527.     /** 
  528.      * 设定Map的值 
  529.      * @param obj 
  530.      * @param jo 
  531.      */  
  532.     private static void setField(Object obj, JSONObject jo) {  
  533.         try {  
  534.             @SuppressWarnings("unchecked")  
  535.             Iterator<String> keyIter = jo.keys();  
  536.             String key;  
  537.             Object value;  
  538.             @SuppressWarnings("unchecked")  
  539.             Map<String, Object> valueMap = (Map<String, Object>) obj;  
  540.             while (keyIter.hasNext()) {  
  541.                 key = (String) keyIter.next();  
  542.                 value = jo.get(key);                  
  543.                 valueMap.put(key, value);  
  544.   
  545.             }  
  546.         } catch (JSONException e) {  
  547.             e.printStackTrace();  
  548.         }  
  549.     }  
  550.       
  551.       
  552.     /** 
  553.      * 设定字段的值 
  554.      * @param obj 
  555.      * @param fieldSetMethod 
  556.      * @param f 
  557.      * @param jo 
  558.      */  
  559.     private static void setField(Object obj, Method fieldSetMethod,Field f, JSONObject jo) {  
  560.         String name = f.getName();  
  561.         Class<?> clazz = f.getType();       
  562.         try {  
  563.             if (isArray(clazz)) { // 数组  
  564.                 Class<?> c = clazz.getComponentType();  
  565.                 JSONArray ja = jo.optJSONArray(name);  
  566.                 if (!isNull(ja)) {  
  567.                     Object array = parseArray(ja, c);  
  568.                     setFiedlValue(obj, fieldSetMethod, clazz.getSimpleName(), array);  
  569.                 }  
  570.             } else if (isCollection(clazz)) { // 泛型集合  
  571.                 // 获取定义的泛型类型  
  572.                 Class<?> c = null;  
  573.                 Type gType = f.getGenericType();  
  574.                 if (gType instanceof ParameterizedType) {  
  575.                     ParameterizedType ptype = (ParameterizedType) gType;  
  576.                     Type[] targs = ptype.getActualTypeArguments();  
  577.                     if (targs != null && targs.length > 0) {  
  578.                         Type t = targs[0];  
  579.                         c = (Class<?>) t;  
  580.                     }  
  581.                 }  
  582.   
  583.                 JSONArray ja = jo.optJSONArray(name);  
  584.                 if (!isNull(ja)) {  
  585.                     Object o = parseCollection(ja, clazz, c);  
  586.                     setFiedlValue(obj, fieldSetMethod, clazz.getSimpleName(), o);  
  587.                 }  
  588.             } else if (isSingle(clazz)) { // 值类型  
  589.                 Object o = jo.opt(name);  
  590.                 if (o != null) {  
  591.                     setFiedlValue(obj, fieldSetMethod, clazz.getSimpleName(), o);  
  592.                 }  
  593.             } else if (isObject(clazz)) { // 对象  
  594.                 JSONObject j = jo.optJSONObject(name);  
  595.                 if (!isNull(j)) {  
  596.                     Object o = parseObject(j, clazz);  
  597.                     setFiedlValue(obj, fieldSetMethod, clazz.getSimpleName(), o);  
  598.                 }  
  599.             } else if (isList(clazz)) { // 列表  
  600. //              JSONObject j = jo.optJSONObject(name);  
  601. //              if (!isNull(j)) {  
  602. //                  Object o = parseObject(j, clazz);  
  603. //                  f.set(obj, o);  
  604. //              }  
  605.             } else {  
  606.                 throw new Exception("unknow type!");  
  607.             }  
  608.         } catch (Exception e) {  
  609.             e.printStackTrace();  
  610.         }  
  611.     }  
  612.       
  613.     /** 
  614.      * 设定字段的值  
  615.      * @param obj 
  616.      * @param f 
  617.      * @param jo 
  618.      */  
  619.     private static void setField(Object obj, Field f, JSONObject jo) {  
  620.         String name = f.getName();  
  621.         Class<?> clazz = f.getType();  
  622.         try {  
  623.             if (isArray(clazz)) { // 数组  
  624.                 Class<?> c = clazz.getComponentType();  
  625.                 JSONArray ja = jo.optJSONArray(name);  
  626.                 if (!isNull(ja)) {  
  627.                     Object array = parseArray(ja, c);  
  628.                     f.set(obj, array);  
  629.                 }  
  630.             } else if (isCollection(clazz)) { // 泛型集合  
  631.                 // 获取定义的泛型类型  
  632.                 Class<?> c = null;  
  633.                 Type gType = f.getGenericType();  
  634.                 if (gType instanceof ParameterizedType) {  
  635.                     ParameterizedType ptype = (ParameterizedType) gType;  
  636.                     Type[] targs = ptype.getActualTypeArguments();  
  637.                     if (targs != null && targs.length > 0) {  
  638.                         Type t = targs[0];  
  639.                         c = (Class<?>) t;  
  640.                     }  
  641.                 }  
  642.   
  643.                 JSONArray ja = jo.optJSONArray(name);  
  644.                 if (!isNull(ja)) {  
  645.                     Object o = parseCollection(ja, clazz, c);  
  646.                     f.set(obj, o);  
  647.                 }  
  648.             } else if (isSingle(clazz)) { // 值类型  
  649.                 Object o = jo.opt(name);  
  650.                 if (o != null) {  
  651.                     f.set(obj, o);  
  652.                 }  
  653.             } else if (isObject(clazz)) { // 对象  
  654.                 JSONObject j = jo.optJSONObject(name);  
  655.                 if (!isNull(j)) {  
  656.                     Object o = parseObject(j, clazz);  
  657.                     f.set(obj, o);  
  658.                 }  
  659.             } else if (isList(clazz)) { // 列表  
  660.                 JSONObject j = jo.optJSONObject(name);  
  661.                 if (!isNull(j)) {  
  662.                     Object o = parseObject(j, clazz);  
  663.                     f.set(obj, o);  
  664.                 }  
  665.             }else {  
  666.                 throw new Exception("unknow type!");  
  667.             }  
  668.         } catch (Exception e) {  
  669.             e.printStackTrace();  
  670.         }  
  671.     }  
  672.   
  673.     /** 
  674.      * 判断对象是否为空 
  675.      * @param obj 
  676.      * @return 
  677.      */  
  678.     private static boolean isNull(Object obj) {  
  679.         if (obj instanceof JSONObject) {  
  680.             return JSONObject.NULL.equals(obj);  
  681.         }  
  682.         return obj == null;  
  683.     }  
  684.   
  685.     /** 
  686.      * 判断是否是值类型  
  687.      * @param clazz 
  688.      * @return 
  689.      */  
  690.     private static boolean isSingle(Class<?> clazz) {  
  691.         return isBoolean(clazz) || isNumber(clazz) || isString(clazz);  
  692.     }  
  693.   
  694.     /** 
  695.      * 是否布尔值 
  696.      * @param clazz 
  697.      * @return 
  698.      */  
  699.     public static boolean isBoolean(Class<?> clazz) {  
  700.         return (clazz != null)  
  701.                 && ((Boolean.TYPE.isAssignableFrom(clazz)) || (Boolean.class  
  702.                         .isAssignableFrom(clazz)));  
  703.     }  
  704.   
  705.     /** 
  706.      * 是否数值  
  707.      * @param clazz 
  708.      * @return 
  709.      */  
  710.     public static boolean isNumber(Class<?> clazz) {  
  711.         return (clazz != null)  
  712.                 && ((Byte.TYPE.isAssignableFrom(clazz)) || (Short.TYPE.isAssignableFrom(clazz))  
  713.                         || (Integer.TYPE.isAssignableFrom(clazz))  
  714.                         || (Long.TYPE.isAssignableFrom(clazz))  
  715.                         || (Float.TYPE.isAssignableFrom(clazz))  
  716.                         || (Double.TYPE.isAssignableFrom(clazz)) || (Number.class  
  717.                         .isAssignableFrom(clazz)));  
  718.     }  
  719.   
  720.     /** 
  721.      * 判断是否是字符串  
  722.      * @param clazz 
  723.      * @return 
  724.      */  
  725.     public static boolean isString(Class<?> clazz) {  
  726.         return (clazz != null)  
  727.                 && ((String.class.isAssignableFrom(clazz))  
  728.                         || (Character.TYPE.isAssignableFrom(clazz)) || (Character.class  
  729.                         .isAssignableFrom(clazz)));  
  730.     }  
  731.   
  732.     /** 
  733.      * 判断是否是对象 
  734.      * @param clazz 
  735.      * @return 
  736.      */  
  737.     private static boolean isObject(Class<?> clazz) {  
  738.         return clazz != null && !isSingle(clazz) && !isArray(clazz) && !isCollection(clazz);  
  739.     }  
  740.   
  741.     /** 
  742.      * 判断是否是数组  
  743.      * @param clazz 
  744.      * @return 
  745.      */  
  746.     public static boolean isArray(Class<?> clazz) {  
  747.         return clazz != null && clazz.isArray();  
  748.     }  
  749.   
  750.     /** 
  751.      * 判断是否是集合 
  752.      * @param clazz 
  753.      * @return 
  754.      */  
  755.     public static boolean isCollection(Class<?> clazz) {  
  756.         return clazz != null && Collection.class.isAssignableFrom(clazz);  
  757.     }  
  758.           
  759.     /** 
  760.      * 判断是否是Map 
  761.      * @param clazz 
  762.      * @return 
  763.      */  
  764.     public static boolean isMap(Class<?> clazz) {  
  765.         return clazz != null && Map.class.isAssignableFrom(clazz);  
  766.     }  
  767.       
  768.     /** 
  769.      * 判断是否是列表  
  770.      * @param clazz 
  771.      * @return 
  772.      */  
  773.     public static boolean isList(Class<?> clazz) {  
  774.         return clazz != null && List.class.isAssignableFrom(clazz);  
  775.     }  
  776.       
  777. }  

 

 

调用测试代码:

 

[java] view plaincopy
  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.     try {  
  21.         User user = new User();  
  22.         user.setName("abcd");  
  23.         user.setPassword("123456");  
  24.           
  25.         User user1 = new User();  
  26.         user.setName("abcdf");  
  27.         user.setPassword("1234567");  
  28.           
  29.         String jsonStrUser = JSONHelper.toJSON(user);   //序列化  
  30.         User jsonUser = JSONHelper.parseObject(jsonStrUser, User.class);    //反序列化        
  31.         Map mapUser = JSONHelper.parseObject(jsonStrUser, HashMap.class);   //反序列化            
  32.           
  33.           
  34.         List sourceList = new ArrayList<User>();  
  35.         sourceList.add(user);  
  36.         sourceList.add(user1);            
  37.         String jsonStrUserList = JSONHelper.toJSON(sourceList);         //序列化  
  38.         List listUser = (List) JSONHelper.parseCollection(jsonStrUserList, List.class, User.class); //反序列化  
  39.     } catch (JSONException e) {  
  40.         e.printStackTrace();  
  41.     }  
  42.       
  43. }  

 

分享到:
评论
1 楼 landerson 2015-02-12  
明显就有要求的嘛

相关推荐

Global site tag (gtag.js) - Google Analytics