_把一个对象转化成map「建议收藏」”>
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;
}
今天的文章object转map
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/69797.html