在项目开发中,经常碰到map转实体对象或者对象转map的场景,工作中,很多时候我们可能比较喜欢使用第三方jar包的API对他们进行转化,而且用起来也还算方便,比如像fastJson就可以轻松实现map和对象的互转,但这里,我想通过反射的方式对他们做转化,也算是对反射的学习和研究吧;
1、map转java对象
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mes.common.core.utils.StringUtils;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @Author: best_liu
* @Description: map转java对象
* @Date: 8:35 2022/3/22
**/
public static Object convertToObject(Class clazz, Map<String, Object> map) throws
IntrospectionException, InstantiationException, IllegalAccessException {
BeanInfo bi = Introspector.getBeanInfo(clazz);
Object obj = clazz.newInstance();
PropertyDescriptor[] pds = bi.getPropertyDescriptors();
String pName;
for (PropertyDescriptor pd : pds) {
pName = pd.getName();
if (map.containsKey(pName)) {
try {
if (pd.getPropertyType().getName().equals("java.lang.Long")) {
if(StringUtils.isNotEmpty(map.get(pName).toString())){
pd.getWriteMethod().invoke(obj, Long.parseLong(map.get(pName).toString()));
}
// else{
// pd.getWriteMethod().invoke(obj, map.get(pName));
// }
} else {
pd.getWriteMethod().invoke(obj, map.get(pName));
}
} catch (Exception ex) {
Logger.getLogger(MapUtil.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return obj;
}
2、java对象转map
/**
* @Author: best_liu
* @Description: java对象转map
* @Date: 8:35 2022/3/22
**/
public static Map<String, String> objectToMap(Object obj) {
if (obj == null) {
return null;
}
Map<String, String> map = new HashMap<String, String>();
try {
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;
String v = null;
if (value != null) {
v = value.toString();
}
map.put(key, v);
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
/**
* @Author: best_liu
* @Description: java对象转map
* @Date: 8:35 2022/3/22
**/
public static Map<String, Object> objectToMapObj(Object obj) {
if (obj == null) {
return null;
}
Map<String, Object> map = new HashMap<String, Object>();
try {
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);
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
3、Map转换为Json字符串文章来源:https://www.toymoban.com/news/detail-648865.html
/**
* @Author: best_liu
* @Description: Map转换为Json字符串
* @Date: 8:35 2022/3/22
**/
public static String mapToJsonString(Map map) {
JSONObject json = new JSONObject();
Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, String> entry = entries.next();
json.put(entry.getKey(), entry.getValue());
}
return json.toString();
}
4、Json字符串转换为Map文章来源地址https://www.toymoban.com/news/detail-648865.html
/**
* @Author: best_liu
* @Description: Json字符串转换为Map
* @Date: 8:35 2022/3/22
**/
public static Map<String, Long> jsonStringToMap(String str) {
Map<String, Long> map = (Map<String, Long>) JSON.parse(str);
return map;
}
到了这里,关于Java中如何优雅的把Map转为对象的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!