最近开发一直使用JSON数据传输,网络中流程的JSON解析导入包太多了,在网上找了下,结合自己改编,简单实现JSON解析,支持集合和对象泛化。
[java] - package com.callgetway.util;
-
- import java.lang.reflect.Array;
- import java.lang.reflect.Field;
- import java.lang.reflect.Method;
- import java.lang.reflect.ParameterizedType;
- import java.lang.reflect.Type;
- import java.text.SimpleDateFormat;
- import java.util.Collection;
- import java.util.Date;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Locale;
- import java.util.Map;
-
- import org.json.JSONArray;
- import org.json.JSONException;
- import org.json.JSONObject;
- import org.json.JSONStringer;
-
- import Android.util.Log;
-
-
- /**
- * @author keane
- * @version 1.0
- *
- */
- public class JSONHelper {
-
- private static String TAG = "JSONHelper";
-
- /**
- * 将对象转换成Json字符串
- * @param obj
- * @return
- */
- public static String toJSON(Object obj) {
- JSONStringer js = new JSONStringer();
- serialize(js, obj);
- Log.d(TAG, "JSONHelper toJSON :" + js.toString());
- return js.toString();
- }
-
- /**
- * 序列化为JSON
- * @param js
- * @param o
- */
- private static void serialize(JSONStringer js, Object o) {
- if (isNull(o)) {
- try {
- js.value(null);
- } catch (JSONException e) {
- e.printStackTrace();
- }
- return;
- }
-
- Class<?> clazz = o.getClass();
- if (isObject(clazz)) { // 对象
- serializeObject(js, o);
- } else if (isArray(clazz)) { // 数组
- serializeArray(js, o);
- } else if (isCollection(clazz)) { // 集合
- Collection<?> collection = (Collection<?>) o;
- serializeCollect(js, collection);
- } else { // 单个值
- try {
- js.value(o);
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- }
-
- /**
- * 序列化数组
- * @param js
- * @param array
- */
- private static void serializeArray(JSONStringer js, Object array) {
- try {
- js.array();
- for (int i = 0; i < Array.getLength(array); ++i) {
- Object o = Array.get(array, i);
- serialize(js, o);
- }
- js.endArray();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- /**
- * 序列化集合
- * @param js
- * @param collection
- */
- private static void serializeCollect(JSONStringer js, Collection<?> collection) {
- try {
- js.array();
- for (Object o : collection) {
- serialize(js, o);
- }
- js.endArray();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- /**
- * 序列化对象
- * @param js
- * @param obj
- */
- private static void serializeObject(JSONStringer js, Object obj) {
- try {
- js.object();
- Class<? extends Object> objClazz = obj.getClass();
- Method[] methods = objClazz.getDeclaredMethods();
- Field[] fields = objClazz.getDeclaredFields();
- for (Field field : fields) {
- try {
- String fieldType = field.getType().getSimpleName();
- String fieldGetName = parseMethodName(field.getName(),"get");
- if (!haveMethod(methods, fieldGetName)) {
- continue;
- }
- Method fieldGetMet = objClazz.getMethod(fieldGetName, new Class[] {});
- Object fieldVal = fieldGetMet.invoke(obj, new Object[] {});
- String result = null;
- if ("Date".equals(fieldType)) {
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
- Locale.US);
- result = sdf.format((Date)fieldVal);
-
- } else {
- if (null != fieldVal) {
- result = String.valueOf(fieldVal);
- }
- }
- js.key(field.getName());
- serialize(js, result);
- } catch (Exception e) {
- continue;
- }
- }
- js.endObject();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- /**
- * 判断是否存在某属性的 get方法
- *
- * @param methods
- * @param fieldGetMet
- * @return boolean
- */
- public static boolean haveMethod(Method[] methods, String fieldMethod) {
- for (Method met : methods) {
- if (fieldMethod.equals(met.getName())) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * 拼接某属性的 get或者set方法
- * @param fieldName
- * @param methodType
- * @return
- */
- public static String parseMethodName(String fieldName,String methodType) {
- if (null == fieldName || "".equals(fieldName)) {
- return null;
- }
- return methodType + fieldName.substring(0, 1).toUpperCase()
- + fieldName.substring(1);
- }
-
-
-
- /**
- * set属性的值到Bean
- * @param obj
- * @param valMap
- */
- public static void setFieldValue(Object obj, Map<String, String> valMap) {
- Class<?> cls = obj.getClass();
- // 取出bean里的所有方法
- Method[] methods = cls.getDeclaredMethods();
- Field[] fields = cls.getDeclaredFields();
-
- for (Field field : fields) {
- try {
- String setMetodName = parseMethodName(field.getName(),"set");
- if (!haveMethod(methods, setMetodName)) {
- continue;
- }
- Method fieldMethod = cls.getMethod(setMetodName, field
- .getType());
- String value = valMap.get(field.getName());
- if (null != value && !"".equals(value)) {
- String fieldType = field.getType().getSimpleName();
- if ("String".equals(fieldType)) {
- fieldMethod.invoke(obj, value);
- } else if ("Date".equals(fieldType)) {
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.US);
- Date temp = sdf.parse(value);
- fieldMethod.invoke(obj, temp);
- } else if ("Integer".equals(fieldType)
- || "int".equals(fieldType)) {
- Integer intval = Integer.parseInt(value);
- fieldMethod.invoke(obj, intval);
- } else if ("Long".equalsIgnoreCase(fieldType)) {
- Long temp = Long.parseLong(value);
- fieldMethod.invoke(obj, temp);
- } else if ("Double".equalsIgnoreCase(fieldType)) {
- Double temp = Double.parseDouble(value);
- fieldMethod.invoke(obj, temp);
- } else if ("Boolean".equalsIgnoreCase(fieldType)) {
- Boolean temp = Boolean.parseBoolean(value);
- fieldMethod.invoke(obj, temp);
- } else {
- System.out.println("setFieldValue not supper type:" + fieldType);
- }
- }
- } catch (Exception e) {
- continue;
- }
- }
-
- }
-
- /**
- * 对象转Map
- * @param obj
- * @return
- */
- public static Map<String, String> getFieldValueMap(Object obj) {
- Class<?> cls = obj.getClass();
- Map<String, String> valueMap = new HashMap<String, String>();
- // 取出bean里的所有方法
- Method[] methods = cls.getDeclaredMethods();
- Field[] fields = cls.getDeclaredFields();
- for (Field field : fields) {
- try {
- String fieldType = field.getType().getSimpleName();
- String fieldGetName = parseMethodName(field.getName(),"get");
- if (!haveMethod(methods, fieldGetName)) {
- continue;
- }
- Method fieldGetMet = cls.getMethod(fieldGetName, new Class[] {});
- Object fieldVal = fieldGetMet.invoke(obj, new Object[] {});
- String result = null;
- if ("Date".equals(fieldType)) {
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.CHINA);
- result = sdf.format((Date)fieldVal);
-
- } else {
- if (null != fieldVal) {
- result = String.valueOf(fieldVal);
- }
- }
- valueMap.put(field.getName(), result);
- } catch (Exception e) {
- continue;
- }
- }
- return valueMap;
-
- }
-
-
-
- /**
- * 给对象的字段赋值
- * @param obj
- * @param fieldSetMethod
- * @param fieldType
- * @param value
- */
- public static void setFiedlValue(Object obj,Method fieldSetMethod,String fieldType,Object value){
-
- try {
- if (null != value && !"".equals(value)) {
- if ("String".equals(fieldType)) {
- fieldSetMethod.invoke(obj, value.toString());
- } else if ("Date".equals(fieldType)) {
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.CHINA);
- Date temp = sdf.parse(value.toString());
- fieldSetMethod.invoke(obj, temp);
- } else if ("Integer".equals(fieldType)
- || "int".equals(fieldType)) {
- Integer intval = Integer.parseInt(value.toString());
- fieldSetMethod.invoke(obj, intval);
- } else if ("Long".equalsIgnoreCase(fieldType)) {
- Long temp = Long.parseLong(value.toString());
- fieldSetMethod.invoke(obj, temp);
- } else if ("Double".equalsIgnoreCase(fieldType)) {
- Double temp = Double.parseDouble(value.toString());
- fieldSetMethod.invoke(obj, temp);
- } else if ("Boolean".equalsIgnoreCase(fieldType)) {
- Boolean temp = Boolean.parseBoolean(value.toString());
- fieldSetMethod.invoke(obj, temp);
- } else {
- fieldSetMethod.invoke(obj, value);
- Log.e(TAG, TAG + ">>>>setFiedlValue -> not supper type" + fieldType);
- }
- }
-
- } catch (Exception e) {
- Log.e(TAG, TAG + ">>>>>>>>>>set value error.",e);
- }
-
- }
-
-
- /**
- * 反序列化简单对象
- * @param jo
- * @param clazz
- * @return
- */
- public static <T> T parseObject(JSONObject jo, Class<T> clazz) {
- if (clazz == null || isNull(jo)) {
- return null;
- }
-
- T obj = newInstance(clazz);
- if (obj == null) {
- return null;
- }
- if(isMap(clazz)){
- setField(obj,jo);
- }else{
- // 取出bean里的所有方法
- Method[] methods = clazz.getDeclaredMethods();
- Field[] fields = clazz.getDeclaredFields();
- for (Field f : fields) {
- String setMetodName = parseMethodName(f.getName(),"set");
- if (!haveMethod(methods, setMetodName)) {
- continue;
- }
- try {
- Method fieldMethod = clazz.getMethod(setMetodName, f.getType());
- setField(obj,fieldMethod,f, jo);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- return obj;
- }
-
-
- /**
- * 反序列化简单对象
- * @param jsonString
- * @param clazz
- * @return
- */
- public static <T> T parseObject(String jsonString, Class<T> clazz) {
- if (clazz == null || jsonString == null || jsonString.length() == 0) {
- return null;
- }
-
- JSONObject jo = null;
- try {
- jo = new JSONObject(jsonString);
- } catch (JSONException e) {
- e.printStackTrace();
- }
-
- if (isNull(jo)) {
- return null;
- }
-
- return parseObject(jo, clazz);
- }
-
- /**
- * 反序列化数组对象
- * @param ja
- * @param clazz
- * @return
- */
- public static <T> T[] parseArray(JSONArray ja, Class<T> clazz) {
- if (clazz == null || isNull(ja)) {
- return null;
- }
-
- int len = ja.length();
-
- @SuppressWarnings("unchecked")
- T[] array = (T[]) Array.newInstance(clazz, len);
-
- for (int i = 0; i < len; ++i) {
- try {
- JSONObject jo = ja.getJSONObject(i);
- T o = parseObject(jo, clazz);
- array[i] = o;
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
-
- return array;
- }
-
-
- /**
- * 反序列化数组对象
- * @param jsonString
- * @param clazz
- * @return
- */
- public static <T> T[] parseArray(String jsonString, Class<T> clazz) {
- if (clazz == null || jsonString == null || jsonString.length() == 0) {
- return null;
- }
- JSONArray jo = null;
- try {
- jo = new JSONArray(jsonString);
- } catch