/**
* @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. LeetCode--不同路径

    一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” ).机器人每次只能向下或者向右移动一步.机器人试图达到网格的右下角(在下图中标记为“Finish”).现在考虑网格中 ...

  2. 五、Scrapy中Item Pipeline的用法

    本文转载自以下链接: https://scrapy-chs.readthedocs.io/zh_CN/latest/topics/item-pipeline.html https://doc.scra ...

  3. gitlab的添加密钥

    1.在本地电脑下载git的客户端并且安装 2.鼠标右键左面选中Git Bash Here 3.操作如下图生成密钥 4.将密钥复制过来添加到gitLab中 5.Eclipse配置密钥 6.在git创建的 ...

  4. Python网络爬虫之Scrapy框架(CrawlSpider)

    目录 Python网络爬虫之Scrapy框架(CrawlSpider) CrawlSpider使用 爬取糗事百科糗图板块的所有页码数据 Python网络爬虫之Scrapy框架(CrawlSpider) ...

  5. 获取当前日期,或指定日期的农历js代码

    时间不早了,直接上代码啦-- var CalendarData=new Array(100);var madd=new Array(12);var tgString="甲乙丙丁戊己庚辛壬癸& ...

  6. Maven学习总结(十一)——Maven项目对象模型pom.xml文件详解

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/20 ...

  7. ReportNG 替换testng过程中遇到的问题

    1. Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/collectio ...

  8. Xmemcached使用之与Spring整合

    转自:http://hi.baidu.com/tjbaso/item/22f3c32b062ebefb50fd87b8 1 简介Xmemcached是一个高性能的基于java nio的memcache ...

  9. MVC.Net:压缩/保存图片缩略图

    通常用户上传的图片需要压缩或者生成缩略图.用System.Web.Helpers.WebImage的Resize方法可以很方便的实现这一功能.示例代码如下: /// <summary> / ...

  10. Java 递归、尾递归、非递归、栈 处理 三角数问题

    import java.io.BufferedReader; import java.io.InputStreamReader; //1,3,6,10,15...n 三角数 /* * # 1 * ## ...