/**
* @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. 蓝桥-区间K大数查询

    问题描述: 给定一个序列,每次询问序列中第l个数到第r个数中第K大的数是哪个. 输入格式 第一行包含一个数n,表示序列长度. 第二行包含n个正整数,表示给定的序列. 第三个包含一个正整数m,表示询问个 ...

  2. JavaScript学习笔记之DOM介绍

    目录 1.简介 2.方法 3.属性 4.访问节点 5.修改节点 6.添加节点 7.删除节点 8.替换节点 9.改变 CSS 1.简介 文档对象模型(Document Object Model,DOM) ...

  3. PHP学习方向-进阶2(三)

    实践篇 给定二维数组,根据某个字段排序 如何判断上传文件类型,如:仅允许 jpg 上传 不使用临时变量交换两个变量的值 $a=1; $b=2; => $a=2; $b=1; strtoupper ...

  4. opcache的配置

    ; Enable Zend OPcache extension module zend_extension=opcache.so ; Determines if Zend OPCache is ena ...

  5. ZOJ 3199 Longest Repeated Substring

    Longest Repeated Substring Time Limit: 5000ms Memory Limit: 32768KB This problem will be judged on Z ...

  6. 洛谷 P1521 求逆序对

    题目描述 我们说(i,j)是a1,a2,…,aN的一个逆序对当且仅当i<j且ai>a j.例如2,4,1,3,5的逆序对有3个,分别为(1,3),(2,3),(2,4).现在已知N和K,求 ...

  7. POJ 3252 Round Numbers 组合数学

    Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 13381   Accepted: 5208 Description The ...

  8. POJ 3061 Subsequence 尺取

    Subsequence Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 14698   Accepted: 6205 Desc ...

  9. [bzoj4010][HNOI2015]菜肴制作_贪心_拓扑排序

    菜肴制作 bzoj-4010 HNOI-2015 题目大意:给定一张n个点m条边的有向图,求一个toposort,使得:(1)满足编号为1的点尽量在前:(2)满足(1)的情况下编号为2的点尽量在前,以 ...

  10. N天学习一个Linux命令之top

    用途 查看机器负载以及进程资源占用情况,linux系统性能分析工具 用法 top -hv | -abcHimMsS -d delay -n iterations -p pid [, pid ...] ...