/**
* @author xxxxxxxxxxx
* @param object
* 待转化类
* @param format自定义转化类型
* @return Map<String,String> 将传入的DTO转化为Map,1、Date转化为String类型的时间戳。 2、null转化为null
* 3、enum通过反射使用getCode()获取code编码。4、其他类型不做转换value=toString()。5、Dto中属性名中的大写字母将被替换为
* "_小写字母"形式,为了与库中返回map一致。
*/
public static Map<String, String> objectToMap(Object object, FormatField format) {
if (object == null) {
return null;
}
Map<String, String> map = new HashMap<String, String>();
Field[] declaredFields = object.getClass().getDeclaredFields();
for (Field field : declaredFields) {
field.setAccessible(true);
try {
String key = field.getName();
if (key.equals("serialVersionUID")) {
continue;
}
String tmpKey=key;
for(int i=0;i<key.length();i++) {
if(Character.isUpperCase(key.charAt(i))) {
tmpKey=tmpKey.replaceAll(""+key.charAt(i), "_"+Character.toLowerCase(key.charAt(i)));
}
}
key=tmpKey;
Object value = field.get(object);
if (format != null) {
value = format.format(key, field.get(object));
}
if (value == null) {
map.put(key, null);
} else if (value instanceof Date) {
map.put(key, String.valueOf(((Date) value).getTime()));
} else if (value.getClass().isEnum()) {
Method method = value.getClass().getMethod("getCode", null);
Object val = method.invoke(value, null);
map.put(key, String.valueOf(val));
} else if (value.getClass().isPrimitive()) {
map.put(key, value + "");
} else {
map.put(key, value.toString());
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
return map;
} public static interface FormatField {
public Object format(String key, Object value);
}

转载:https://www.cnblogs.com/dreammyle/p/5610906.html

/**
* 使用org.apache.commons.beanutils进行转换
*/
class A { public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
if (map == null)
return null; Object obj = beanClass.newInstance(); org.apache.commons.beanutils.BeanUtils.populate(obj, map); return obj;
} public static Map<?, ?> objectToMap(Object obj) {
if(obj == null)
return null; return new org.apache.commons.beanutils.BeanMap(obj);
} } /**
* 使用Introspector进行转换
*/
class B { public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
if (map == null)
return null; Object obj = beanClass.newInstance(); BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
Method setter = property.getWriteMethod();
if (setter != null) {
setter.invoke(obj, map.get(property.getName()));
}
} return obj;
} public static Map<String, Object> objectToMap(Object obj) throws Exception {
if(obj == null)
return null; Map<String, Object> map = new HashMap<String, Object>(); BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
if (key.compareToIgnoreCase("class") == 0) {
continue;
}
Method getter = property.getReadMethod();
Object value = getter!=null ? getter.invoke(obj) : null;
map.put(key, value);
} return map;
} } /**
* 使用reflect进行转换
*/
class C { public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
if (map == null)
return null; Object obj = beanClass.newInstance(); Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
int mod = field.getModifiers();
if(Modifier.isStatic(mod) || Modifier.isFinal(mod)){
continue;
} field.setAccessible(true);
field.set(obj, map.get(field.getName()));
} return obj;
} public static Map<String, Object> objectToMap(Object obj) throws Exception {
if(obj == null){
return null;
} Map<String, Object> map = new HashMap<String, Object>(); Field[] declaredFields = obj.getClass().getDeclaredFields();
for (Field field : declaredFields) {
field.setAccessible(true);
map.put(field.getName(), field.get(obj));
} return map;
}
}

java bean转Map的更多相关文章

  1. Java bean 转 Map

    Java bean 转 Map 时需要使用Fastjson //方法 一 Map<String, Object> a = (Map<String, Object>)JSON.t ...

  2. Java Bean与Map之间相互转化的实现

    目录树 概述 Apache BeanUtils将Bean转Map Apache BeanUtils将Map转Bean 理解BeanUtils将Bean转Map的实现之手写Bean转Map 概述 Apa ...

  3. Bean与Map的转换 和 Map与Bean的转换

    package com.JUtils.beanConvert; import java.beans.BeanInfo; import java.beans.IntrospectionException ...

  4. java bean、List、数组、map和Json的相互转化

    工程 json包为  代码 package com.my.json; public class ChildBean { private String childName; private String ...

  5. java的bean和map互转的工具类

    import java.beans.BeanInfo;import java.beans.IntrospectionException;import java.beans.Introspector;i ...

  6. java中 json和bean list map之间的互相转换总结

    JSON 与 对象 .集合 之间的转换 JSON字符串和java对象的互转[json-lib]   在开发过程中,经常需要和别的系统交换数据,数据交换的格式有XML.JSON等,JSON作为一个轻量级 ...

  7. Java中将JSON格式的数据转换成对应的Bean、Map、List数据

    简单说明: 为了方便数据在客户端及服务器端的传输,有时候我们会用一些比较方便组织的数据类型,比如json.xml等传给客户端,客户端也可以重新组织数据传回服务器端.JSON和XML提供了一套比较方便的 ...

  8. bean 与 map 互转.

    package com.sprucetec.tms.distribute.utils;import java.beans.BeanInfo;import java.beans.Introspectio ...

  9. 深入了解数据校验:Java Bean Validation 2.0(JSR380)

    每篇一句 吾皇一日不退役,尔等都是臣子 相关阅读 [小家Java]深入了解数据校验(Bean Validation):基础类打点(ValidationProvider.ConstraintDescri ...

随机推荐

  1. LNMP动态网站架构及web应用部署,搭建discuz论坛

    1)部署Nginx 实验tar安装包可找本人拿记得点+关注,感谢亲们支持,评论拿包 systemctl stop firewalld iptables -F setenforce 0 1)安装支持软件 ...

  2. 多目标跟踪笔记二:Efficient Algorithms for Finding the K Best Paths Through a Trellis

    Abstract 本文提出了一种新的方法来寻找不相交k最优路径.最坏情况下计算复杂度为N3log(N).该方法比WVD算法(https://www.cnblogs.com/walker-lin/p/1 ...

  3. $(document).ready(function(){}) 与 window.onload = function(){} 区别

    $(document).ready(fucntion(){ //在页面dom结构加载完毕后执行代码, }) window.onload = function(){ //页面所有内容加载完毕后,执行代码 ...

  4. 2.使用term filter搜索数据

    主要知识点 根据用户ID.是否隐藏.帖子ID.发帖日期来搜索帖子 一.准备数据 1.插入一些测试帖子数据     POST /forum/article/_bulk { "index&quo ...

  5. css3 background-clip和background-origin 区别

    在css3中,background-clip和background-origin它们2个的功能大致相同,但又有些细微差别. 1.background-clip:规定背景的绘制区域,当背景是纯颜色时与图 ...

  6. python之cookbook-day04

    第一章:数据结构和算法 1.4 查找最大或最小的N个元素 问题: 怎样从一个集合中获得最大或者最小的 N 个元素列表? 解决方案: heapq 模块有两个函数:nlargest() 和 nsmalle ...

  7. 解决Eclipse导入项目后Validating验证缓慢的问题

    减少不必要的验证即可 步骤:Window-Preferences-左侧的Validation 如图所示,将Build一列的勾全部去掉就好了. 如需手动校验,右键项目名-选择Validate即可.

  8. springmvc mybatis 分页插件 pagehelper

    springmvc mybatis 分页插件 pagehelper 下载地址:pagehelper 4.2.1 , jsqlparser 0.9.5 https://github.com/pagehe ...

  9. Android Studio第一次启动的Fetching android sdk component information的问题

    1)进入刚安装的Android Studio文件夹下的bin文件夹.找到idea.properties文件,用文本编辑器打开. 2)在idea.properties文件末尾加入一行: disable. ...

  10. javaEE之--------统计站点在线人数,安全登录等(观察者设计模式)

    整体介绍下:  监听器:监听器-就是一个实现待定接口的普通Java程序,此程序专门用于监听别一个类的方法调用.都是使用观察者设计模式. 小弟刚接触这个,做了些简单的介绍.大神请绕道,技术仅仅是一点点, ...