参考:https://blog.csdn.net/segegefe/article/details/123942010

方式一: 利用FastJson 把对象转化为Map

引入依赖

  1. <!--操作JSON字符串-->
  2. <dependency>
  3. <groupId>com.alibaba</groupId>
  4. <artifactId>fastjson</artifactId>
  5. <version>1.2.80</version>
  6. </dependency>
  1. @Override
  2. public List<Map> getTreeMenu(VueMenu vueMenu) {
  3. List<Map> list = new ArrayList<>();
  4. //构造条件构造器
  5. LambdaQueryWrapper<VueMenu> lqw = new LambdaQueryWrapper();
  6. //添加过滤条件
  7. lqw.eq(VueMenu::getTjclass, 1);
  8. lqw.eq(VueMenu::getParent, vueMenu.getId());
  9. lqw.orderByAsc(VueMenu::getSortnum);
  10. //查询出符合条件的菜单数据多条
  11. List<VueMenu> vueMenus = vueMenuMapper.selectList(lqw);
  12. if (vueMenus.size() > 0) {
  13. vueMenus.forEach(item -> {
  14. Map<String, Object> map = new HashMap<String, Object>();
  15. //Java对象转JSON字符串
  16. String json = JSON.toJSONString(item);
  17. log.info("json字符串:{}", json);
  18. //把JSON字符串转成JSON对象,再传给map
  19. map = JSON.parseObject(json);
  20. //递归调用
  21. List<Map> treeMenu = getTreeMenu(item);
  22. //如果递归有值,则把值传给“children”key,并put到map中
  23. if (treeMenu != null) map.put("children", treeMenu);
  24. System.out.println("map = " + map);
  25. //添加到List集合中
  26. list.add(map);
  27. });
  28. }
  29. return list;
  30. }

方式二: 利用反射进行转换

  1. public class BeanMapUtilByReflect {
  2. /**
  3. * 对象转Map
  4. * @param object
  5. * @return
  6. * @throws IllegalAccessException
  7. */
  8. public static Map beanToMap(Object object) throws IllegalAccessException {
  9. Map<String, Object> map = new HashMap<String, Object>();
  10. Field[] fields = object.getClass().getDeclaredFields();
  11. for (Field field : fields) {
  12. field.setAccessible(true);
  13. map.put(field.getName(), field.get(object));
  14. }
  15. return map;
  16. }
  17. /**
  18. * map转对象
  19. * @param map
  20. * @param beanClass
  21. * @param <T>
  22. * @return
  23. * @throws Exception
  24. */
  25. public static <T> T mapToBean(Map map, Class<T> beanClass) throws Exception {
  26. T object = beanClass.newInstance();
  27. Field[] fields = object.getClass().getDeclaredFields();
  28. for (Field field : fields) {
  29. int mod = field.getModifiers();
  30. if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
  31. continue;
  32. }
  33. field.setAccessible(true);
  34. if (map.containsKey(field.getName())) {
  35. field.set(object, map.get(field.getName()));
  36. }
  37. }
  38. return object;
  39. }
  40. }

Map转Java对象

先把map转换成JSON字符串,再通过JSON字符串解析成JAVA对象