Map-JSON-对象 三者转换
Map转对象
方法一:使用BeanUtils工具类
org.apache.commons.beanutils.BeanUtils的populate方法
方法 | ||
---|---|---|
BeanUtils对象 | populate(Object bean, Map<String,String[]>properties) | 将Map数据封装到指定Javabean中,一般用于将表单的所有数据封装到javabean |
setProperty(Object obj,String name,Object value) | 设置属性值 | |
getProperty(Object obj,String name) | 获得属性值 |
示例:
方法二:反射
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;
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;
}
方法三:自写工具类
public static void copyMapToObject(Map<String, String> map, Object o) {
Set<String> set = map.keySet();
Class c = o.getClass();
Field[] fields = c.getDeclaredFields();
for (Field f : fields) {
f.setAccessible(true);
if (set.contains(f.getName())){
try {
f.set(o, map.get(f.getName()));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
Map转JSON
Map转json字符串
方法一:导入阿里巴巴fastjson依赖包:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.24</version>
</dependency>
Map map=new HashMap();
map.put("page_size","10");
map.put("page_index","1");
String param= JSON.toJSONString(map);
方法二:遍历map取值转换
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();
}
Map转json数组
导入阿里巴巴fastjson依赖包:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.24</version>
</dependency>
Map map=new HashMap();
map.put("page_size","10");
map.put("page_index","1");
JSONArray jArray = new JSONArray();
jArray.add(map);
String str = jArray.toString();
对象转Map
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;
}
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;
}
JSON转Map
JSON字符串转Map
public static Map<String, Long> jsonStringToMap(String str) {
Map<String, Long> map = (Map<String, Long>) JSON.parse(str);
return map;
}
JSON字符串转JSONObject
private JSONObject StringToJSONObject(String requestData) {
try{
JSONObject jsonObject = new JSONObject(requestData);
return jsonObject;
}catch (Exception e){
//说明字符串不是JSON格式数据
return null;
}
}