FindArchiveDto findArchiveDto= new FindArchiveDto();
findArchiveDto.setContractStatus("降龙");
findArchiveDto.setCustName("明华");
findArchiveDto.setDepartmentName("赵无极"); ```
>fastjson转换方法
//Object转Map Map map JSONObject
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的转换
//对象转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;
}