主要使用了2个类 JsonConvert.class 和 ConvertHelper.class
由于常规转json。只要model牵涉到复杂的关联实体对象。那么就会出现 深度循环的错误。
因此这里通过ConvertHelper.class来解决 深度循环的控制次数。
这个ConvertHelper.class也是同事网上找的,效率上可能慢了点。
但是一般转json,我的项目中都是为了存放到redis缓存的。所以之后也就不存在转换的情况了。
JsonConvert.class
import java.util.List; import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import com.kintech.common.utils.log.LogerHelper; import org.codehaus.jackson.map.DeserializationConfig; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig; import org.codehaus.jackson.type.JavaType; import org.codehaus.jackson.type.TypeReference; public class JsonConvert { private static final Logger logger = Logger.getLogger(JsonConvert.class); private static final ObjectMapper mapper = new ObjectMapper(); //转换器 static{
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(DeserializationConfig.Feature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true) ;
mapper.disable(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS); //忽略映射属性
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
} /** * java对象(包括list)转json * @throws Exception */ public static String toJSON(Object object){ try { return mapper.writeValueAsString(object); } catch (Exception e) { //e.printStackTrace(); LogerHelper.WebLog(LogerHelper.getPrintStr(e)); return null; } } /** * 针对hibernate关联model深度循环转json * @throws Exception */ public static String toHJSON(Object object,int layer){ try { if(object instanceof List){ object = ConverHelper.getListCopy((List)object, layer); }else if(object instanceof Set){ object = ConverHelper.getSetCopy((Set)object, layer); }else{ object = ConverHelper.getCopy(layer,object); } return mapper.writeValueAsString(object); } catch (Exception e) { //e.printStackTrace(); LogerHelper.WebLog(LogerHelper.getPrintStr(e)); return null; } } /** * 针对hibernate关联model深度循环转json * @throws Exception */ public static String toHJSON(Object object){ try { if(object instanceof List){ object = ConverHelper.getListCopy((List)object); }else if(object instanceof Set){ object = ConverHelper.getSetCopy((Set)object); }else{ object = ConverHelper.getCopy(object); } return mapper.writeValueAsString(object); } catch (Exception e) { //e.printStackTrace(); LogerHelper.WebLog(LogerHelper.getPrintStr(e)); return null; } } /** * json转java对象 * @param json * @param cs * @throws Exception */ public static <T> T fromJson(String json, Class<T> cs) { try { return mapper.readValue(json, cs); } catch (Exception e) { //e.printStackTrace(); LogerHelper.WebLog(LogerHelper.getPrintStr(e)); return null; } } /** * json转java对象(Model中含有List<T>) * 针对错误:java.util.LinkedHashMap cannot be cast to ..... * @param json * @param cs * @throws Exception */ public static <T> T fromJson(String json, TypeReference<T> cs) { try { return mapper.readValue(json, cs); } catch (Exception e) { //e.printStackTrace(); throw new RuntimeException(MESSAGE); } } /** * json转map * @param json * @param cs * @return * @throws Exception */ public static Map toMap(String json, Class<Map> cs) { try { return mapper.readValue(json, cs); } catch (Exception e) { //e.printStackTrace(); LogerHelper.WebLog(LogerHelper.getPrintStr(e)); return null; } } /** * json转list * @param json * @param beanClass * @return * @throws Exception */ public static <T> List<T> jsonToList(String json, Class<T> beanClass) { try { return (List<T>) mapper.readValue(json, getCollectionType(List.class, beanClass)); } catch (Exception e) { //e.printStackTrace(); LogerHelper.WebLog(LogerHelper.getPrintStr(e)); return null; } } public static JavaType getCollectionType(Class<?> collectionClass, Class<?> elementClasses) { return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses); } }
ConvertHelper(类名不要带 _ )
package com.kps.common.utils; import java.io.ObjectInputStream.GetField; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.log4j.Logger; import org.hibernate.collection.internal.PersistentBag; import org.hibernate.collection.internal.PersistentMap; import org.hibernate.collection.internal.PersistentSet; import com.kps.model.SuperBaseModel; /** * 按层次copy hibernate对象 * */ @SuppressWarnings("all") public class ConverHelper{ private static final Logger logger = Logger.getLogger(ConverHelper.class); private static String MESSAGE = "copy object error!"; private static int LAYER =3; /** * 得到属性(包括父类) */ private static List<Field> getFields(Class cs){ List<Field> fieldList = new ArrayList<>() ; Class tempClass = cs; while (tempClass != null) {//当父类为null的时候说明到达了最上层的父类(Object类). fieldList.addAll(Arrays.asList(tempClass.getDeclaredFields())); tempClass = tempClass.getSuperclass(); //得到父类,然后赋给自己 } return fieldList; } /** * 最核心的方法,用来解析hibernate model; * @param layer 解析深度 * @param t 为hibernate model * */ public static <T> T getCopy(T t,int...layers) { if (t == null) return null; if (t instanceof SuperBaseModel) { //如果为hibernate映射model int layer = LAYER; if (layers != null && layers.length > 0) { layer = layers[0]; } if (layer > 0) { layer--; } else { return null; } try { Class<?> oClass = (Class<?>) t.getClass(); String className = oClass.getName(); // 通过观察发现代理对象(懒加载)和实体对象是有关联的 // 规律大概是“类名_字符串”,这样可以通过传入对象取实体对象的类名(包括传入实体对象); // 懒加载为代理对象不让查询数据库 if(className.indexOf("_")>=0) return null; String entityClassName = className.split("_")[0]; Class entityClass = Class.forName(entityClassName);// 获取实体对象class实例 Object newT = entityClass.newInstance();// 创建实体对象用于储存传入对象信息; List<Field> fields = getFields(entityClass); for (Field f : fields) { // 反射获取对象属性拼出get、set方法 String fieldName = f.getName(); if (fieldName.equalsIgnoreCase("serialVersionUID")) { continue; } String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); String setMethodName = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); Method getMethod = oClass.getMethod(getMethodName); Object obj = getMethod.invoke(t);// 获取属性的值 if (obj != null) { /* * System.out.println("转换"+obj); * System.out.println("转换"+obj.getClass()); * System.out.println("转换"+ntClass); */ /* * logger.info("转换" + obj); logger.info("转换" + * obj.getClass()); logger.info("转换" + ntClass); */ // 通过观察发现代理对象(懒加载)和实体对象是有关联的 // 规律大概是“类名_字符串”,这样可以通过传入对象取实体对象的类名(包括传入实体对象); String objClassName = obj.getClass().getName().split("_")[0]; Class objClass = Class.forName(objClassName); if (objClass.isAssignableFrom(PersistentSet.class)||objClass.isAssignableFrom(HashSet.class))// 关联查询属性是set hibernate返回的是PersistentSet objClass = Set.class; else if (objClass.isAssignableFrom(PersistentBag.class)||objClass.isAssignableFrom(ArrayList.class))//关联查询属性是list hibernate返回的是PersistentBag objClass = List.class; else if (objClass.isAssignableFrom(PersistentMap.class)||objClass.isAssignableFrom(HashMap.class))//关联查询属性是Map hibernate返回的是PersistentMap objClass = Map.class; else if (objClass.isAssignableFrom(Timestamp.class))// 处理数据库取到时间的问题 objClass = Date.class; Method setmethod = entityClass.getMethod(setMethodName, objClass);// 获取实体类中的set方法; if (obj instanceof Set) { //如果属于set调用getSetCopy方法 Set<Object> set = (Set<Object>) obj; setmethod.invoke(newT, getSetCopy(set, layer)); } else if (obj instanceof List) { //如果属于list调用getListCopy方法 List<Object> list = (List<Object>) obj; setmethod.invoke(newT, getListCopy(list, layer)); } else if (obj instanceof Map) { //如果属于map调用getMapCopy方法 Map map = (Map)obj; setmethod.invoke(newT, getMapCopy(map, layer)); }else {// 属于其他类型 setmethod.invoke(newT, getCopy(obj, layer)); } } } return (T) newT; } catch (Exception e) { logger.error(LogerHelper.getPrintStr(e)); throw new RuntimeException(MESSAGE); } }else{ return t; } } /** * @param layer * @param T 为hibernate model * @return */ public static <T> Set<T> getSetCopy(Set<T> set, int...layers) { if(set==null) return null; int layer = LAYER; if(layers!=null&&layers.length>0){ layer = layers[0]; } // if (layer > 0) { // layer--; // } else { // return null; // } Set<T> newSet = new HashSet<T>(); for (T obj : set) { newSet.add(getCopy(obj,layer)); } return newSet; } /** * @param layer * @param T 为hibernate model */ public static <T> List<T> getListCopy(List<T> list, int...layers) { if (list == null) return null; int layer = LAYER; if(layers!=null&&layers.length>0){ layer = layers[0]; } /* if (layer > 0) { layer--; } else { return null; }*/ ArrayList<T> arrayList = new ArrayList<T>(); for (T obj : list) { arrayList.add(getCopy(obj,layer)); } return arrayList; } /** * @param layer * @param T 为hibernate model */ public static <K,V> Map<K,V> getMapCopy(Map<K,V> map, int...layers) { if (map == null) return null; int layer = LAYER; if(layers!=null&&layers.length>0){ layer = layers[0]; } /* if (layer > 0) { layer--; } else { return null; }*/ Map<K,V> rMap = new HashMap<K, V>(); for (K key : map.keySet()) { rMap.put(key, getCopy(map.get(key),layer)); } return rMap; } }