大家好,又见面了,我是你们的朋友全栈君。
FindArchiveDto findArchiveDto = new FindArchiveDto();
findArchiveDto.setContractStatus("降龙");
findArchiveDto.setCustName("明华");
findArchiveDto.setDepartmentName("赵无极");
fastjson转换方法
//Object转Map
Map map = JSONObject.parseObject(JSONObject.toJSONString(findArchiveDto), Map.class);
Map<String,Object> map = JSONObject.parseObject(JSON.toJSONString(findArchiveDto));
//Map转Object
FindArchiveDto findArchiveDto1 = JSON.parseObject(JSON.toJSONString(map), FindArchiveDto.class);
FindArchiveDto findArchiveDto2 = JSONObject.toJavaObject(JSON.toJSONString(map), FindArchiveDto.class);
jackson的转换
ObjectMapper mapper = new ObjectMapper();
//对象转map
Map m = mapper.readValue(mapper.writeValueAsString(findArchiveDto), Map.class);
//map转对象
FindArchiveDto dto = mapper.readValue(mapper.writeValueAsString(m), FindArchiveDto.class);
还可以用org.apache.commons.beanutils.BeanMap进行转换
Map<String, Object> map = new org.apache.commons.beanutils.BeanMap(findArchiveDto);
还可以用org.apache.commons.beanutils.BeanUtils将map转为对象
BeanUtils.populate(findArchiveDto, 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;
}
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/130464.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...