第一种方法:fastJosn
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject;Object转Map
FindArchiveDto findArchiveDto = new FindArchiveDto(); findArchiveDto.setContractStatus("降龙"); findArchiveDto.setCustName("明华"); findArchiveDto.setDepartmentName("赵无极"); Map map = JSONObject.parseObject(JSONObject.toJSONString(findArchiveDto), Map.class); Map<String,Object> map = JSONObject.parseObject(JSON.toJSONString(findArchiveDto));还可以用org.apache.commons.beanutils.BeanMap进行转换
Map<String, Object> map = new org.apache.commons.beanutils.BeanMap(findArchiveDto);Map转Object
Map maps = new HashMap(); maps.put("contractStatus", "降龙"); map.put("custName", "明华"); map.put("departmentName", "赵无极"); FindArchiveDto findArchiveDto1 = JSON.parseObject(JSON.toJSONString(maps), FindArchiveDto.class);还可以用BeanUtils.populate()将map转为对象
FindArchiveDto dto = new FindArchiveDto(); BeanUtils.populate(dto, map);第二种方法:
//Object转Map public static Map<String, Object> getObjectToMap(Object obj) throws IllegalAccessException { Map<String, Object> map = new LinkedHashMap<String, Object>(); Class<?> clazz = obj.getClass(); System.out.println(clazz); for (Field field : clazz.getDeclaredFields()) { field.setAccessible(true); String fieldName = field.getName(); Object value = field.get(obj); if (value == null){ value = ""; } map.put(fieldName, value); } return map; } //Map转Object public static Object mapToObject(Map<Object, 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); if (map.containsKey(field.getName())) { field.set(obj, map.get(field.getName())); } } return obj; }