1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
public static <T> List<T> tree(Object obj, String parentCodeFieldName, String parentCode, String currentCodeFieldName, String childrenFiledName, Class<T> c) { long t1 = System.currentTimeMillis(); String jsonStr = JSON.toJSONString(obj); log.debug("树转换开始 >>>>>>>>>>>>>>>> {}", JSON.toJSONString(obj)); JSONArray jsonArray = (JSONArray) JSONPath.read(jsonStr, "$[" + parentCodeFieldName + "=" + parentCode + "]"); if (CollectionUtils.isEmpty(jsonArray)) { return Lists.newArrayList(); } for (int i = 0; i < jsonArray.size(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); String code = jsonObject.getString(currentCodeFieldName); treeChildren(jsonStr, jsonObject, parentCodeFieldName, code, currentCodeFieldName, childrenFiledName); } List<T> list = JSONArray.parseArray(jsonArray.toString(), c); log.debug("树转换结束, 转换时间: {} ms . >>>>>>>>>>>>>>>> {}", (System.currentTimeMillis() - t1), JSON.toJSONString(list)); return list; }
private static void treeChildren(String jsonStr, JSONObject currentJsonObj, String parentCodeFieldName, String parentCode, String currentCodeFieldName, String childrenFiledName) { JSONArray jsonArray = (JSONArray) JSONPath.read(jsonStr, "$[" + parentCodeFieldName + "=" + parentCode + "]"); if (CollectionUtils.isEmpty(jsonArray)) { return; } currentJsonObj.put(childrenFiledName, jsonArray); for (int i = 0; i < jsonArray.size(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); String code = jsonObject.getString(currentCodeFieldName); treeChildren(jsonStr, jsonObject, parentCodeFieldName, code, currentCodeFieldName, childrenFiledName); } }
|