参考:https://blog.csdn.net/segegefe/article/details/123942010
方式一: 利用FastJson 把对象转化为Map
引入依赖
<!--操作JSON字符串--><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.80</version></dependency>
@Overridepublic List<Map> getTreeMenu(VueMenu vueMenu) {List<Map> list = new ArrayList<>();//构造条件构造器LambdaQueryWrapper<VueMenu> lqw = new LambdaQueryWrapper();//添加过滤条件lqw.eq(VueMenu::getTjclass, 1);lqw.eq(VueMenu::getParent, vueMenu.getId());lqw.orderByAsc(VueMenu::getSortnum);//查询出符合条件的菜单数据多条List<VueMenu> vueMenus = vueMenuMapper.selectList(lqw);if (vueMenus.size() > 0) {vueMenus.forEach(item -> {Map<String, Object> map = new HashMap<String, Object>();//Java对象转JSON字符串String json = JSON.toJSONString(item);log.info("json字符串:{}", json);//把JSON字符串转成JSON对象,再传给mapmap = JSON.parseObject(json);//递归调用List<Map> treeMenu = getTreeMenu(item);//如果递归有值,则把值传给“children”key,并put到map中if (treeMenu != null) map.put("children", treeMenu);System.out.println("map = " + map);//添加到List集合中list.add(map);});}return list;}
方式二: 利用反射进行转换
public class BeanMapUtilByReflect {/*** 对象转Map* @param object* @return* @throws IllegalAccessException*/public static Map beanToMap(Object object) throws IllegalAccessException {Map<String, Object> map = new HashMap<String, Object>();Field[] fields = object.getClass().getDeclaredFields();for (Field field : fields) {field.setAccessible(true);map.put(field.getName(), field.get(object));}return map;}/*** map转对象* @param map* @param beanClass* @param <T>* @return* @throws Exception*/public static <T> T mapToBean(Map map, Class<T> beanClass) throws Exception {T object = beanClass.newInstance();Field[] fields = object.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(object, map.get(field.getName()));}}return object;}}
Map转Java对象
先把map转换成JSON字符串,再通过JSON字符串解析成JAVA对象
