Map支持path路径查询数据
public static Object getPath(Map<String, Object> map, String path) { if (path == null || path.length() == 0) { return null; } String[] paths = path.split("\\."); Object newObj = null; for (int i = 0; i < paths.length; i++) { String s = paths[i]; if (i == 0) { newObj = map.get(s); continue; } newObj = getObject(newObj, s); } return newObj; } private static Object getObject(Object newObj, String s) { if (newObj instanceof Map) { return ((Map) newObj).get(s); } if (newObj instanceof List) { List<Object> list = new ArrayList<>(); List<Object> o = (List<Object>) newObj; for (Object object : o) { list.add(getObjectFromList(object, s)); } return list; } if (newObj instanceof JSONObject) { return ((JSONObject) newObj).getInnerMap().get(s); } if (newObj instanceof JSONArray) { List<Object> list = new ArrayList<>(); List<Map> o = (List<Map>) newObj; for (Map map1 : o) { list.add(map1.get(s)); } return list; } return newObj; } public static Object getObjectFromList(Object object, String s) { if (object instanceof Map) { return ((Map) object).get(s); } if (object instanceof List) { List<Object> list = new ArrayList<>(); List<Object> o1 = (List<Object>) object; for (Object o2 : o1) { list.add(getObjectFromList(o2, s)); } return list; } return object; }
public static void main(String[] args) throws Exception { //Map maps = (Map<String, Object>) JSON.parseObject(json, Map.class); Map<String, Object> maps = new HashMap<>(); Map<String, Object> a1 = new HashMap<>(); List<Map<String, Object>> list1 = new ArrayList<>(); Map<String, Object> a4 = new HashMap<>(); a4.put("test", "cs"); list1.add(a4); Map<String, Object> a5 = new HashMap<>(); a5.put("test", "cf"); list1.add(a5); a1.put("materialClass", list1); Map<String, Object> a2 = new HashMap<>(); List<Map<String, Object>> list2 = new ArrayList<>(); Map<String, Object> a6 = new HashMap<>(); a6.put("test", "aa"); list2.add(a6); Map<String, Object> a7 = new HashMap<>(); a7.put("test", "bb"); list2.add(a7); a2.put("materialClass", list2); List<Map<String, Object>> list = new ArrayList<>(); list.add(a1); list.add(a2); Map<String, Object> a3 = new HashMap<>(); a3.put("subList", list); maps.put("data", a3); //System.out.println(jsonMapper.writeValueAsString(maps)); Object o = getPath(maps, "data.subList.materialClass"); //Object o1 = getPath(maps, "data.subList"); //Map<String, Object> root = new HashMap<>(); //set(root, "test.a", o1); //System.out.println(jsonMapper.writeValueAsString(root)); // // //set(root, "test.a.materialClass.test", "aa"); //System.out.println(jsonMapper.writeValueAsString(root)); }
主要解决了子表嵌套获取不到数据的问题。