Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / 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