FindArchiveDto findArchiveDto = new FindArchiveDto();findArchiveDto.setContractStatus("降龙");findArchiveDto.setCustName("明华");findArchiveDto.setDepartmentName("赵无极");
fastjson转换方法
//Object转MapMap map = JSONObject.parseObject(JSONObject.toJSONString(findArchiveDto), Map.class);Map map = JSONObject.parseObject(JSON.toJSONString(findArchiveDto));//Map转ObjectFindArchiveDto findArchiveDto1 = JSON.parseObject(JSON.toJSONString(map), FindArchiveDto.class);FindArchiveDto findArchiveDto2 = JSONObject.toJavaObject(JSON.toJSONString(map), FindArchiveDto.class);
jackson的转换
ObjectMapper mapper = new ObjectMapper();//对象转mapMap m = mapper.readValue(mapper.writeValueAsString(findArchiveDto), Map.class);//map转对象FindArchiveDto dto = mapper.readValue(mapper.writeValueAsString(m), FindArchiveDto.class);
还可以用org.apache.commons.beanutils.BeanMap进行转换
Map map = new org.apache.commons.beanutils.BeanMap(findArchiveDto);
还可以用org.apache.commons.beanutils.BeanUtils将map转为对象
BeanUtils.populate(findArchiveDto, map);
//Object转Mappublic static Map getObjectToMap(Object obj) throws IllegalAccessException { Map map = new LinkedHashMap(); 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转Objectpublic static Object mapToObject(Map 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和Map转Object(对象转map,map转对象)
最新推荐文章于 2024-06-05 16:20:06 发布