Object转换成Map(支持驼峰,下划线)
Posted lingtiaoti
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Object转换成Map(支持驼峰,下划线)相关的知识,希望对你有一定的参考价值。
一.Object转换成Map,支持下划线转换成map
import com.google.common.base.CaseFormat; import com.google.common.base.Converter; class Utils{ private static Converter<String, String> converter = CaseFormat.LOWER_CAMEL.converterTo(CaseFormat.UPPER_UNDERSCORE); //Object转换为Map(实体对象转换成带下划线的map) public static Map<String,Object> objToMap(Object obj) throws Exception{ Map<String,Object> map = new LinkedHashMap<String, Object>(); Field[] fields = obj.getClass().getDeclaredFields(); for(Field field : fields){ field.setAccessible(true); map.put(converter.convert(field.getName()) , field.get(obj)); } return map; } }
二.驼峰与下划线方式名称互相转换工具类
public class CamelUnderlineUtil { private static final char UNDERLINE =‘_‘; public static String camelToUnderline(String param) { if (StringUtil.isEmpty(param)) { return ""; } StringBuilder sb = new StringBuilder(); int len = param.length(); for (int i = 0; i < len; i++) { char c = param.charAt(i); if (Character.isUpperCase(c)) { sb.append(UNDERLINE); sb.append(Character.toLowerCase(c)); } else { sb.append(c); } } return sb.toString(); } public static String underlineToCamel(String param){ if (StringUtil.isEmpty(param)) { return ""; } StringBuilder sb = new StringBuilder(); int len = param.length(); for (int i = 0; i < len; i++) { char c = param.charAt(i); if (c==UNDERLINE) { if(++i<len){ sb.append(Character.toUpperCase(param.charAt(i))); } } else { sb.append(c); } } return sb.toString(); } }
三.Bean对象转Map方法
private Map<String, String> convertObjectToMap(Object obj, Class clazz) throws Exception { Map<String, String> dstMap = new HashMap<String, String>(); Field[] fields = obj.getClass().getDeclaredFields(); for (Field field : fields) { if ("serialVersionUID".equals(field.getName())) { continue; } String dstName = CamelUnderlineUtil.camelToUnderline(field.getName()); PropertyDescriptor pd; pd = new PropertyDescriptor(field.getName(), clazz); Method method = pd.getReadMethod(); Object dstObject = method.invoke(obj); if (dstObject instanceof Date) { dstObject = convertToTimeStamp16((Date) dstObject); } if (dstObject instanceof ArrayList) { dstObject = ""; } dstMap.put(dstName, StringUtil.isEmpty(dstObject) ? "" : dstObject.toString()); } return dstMap; }
以上是关于Object转换成Map(支持驼峰,下划线)的主要内容,如果未能解决你的问题,请参考以下文章