Java 格式化json为json树
/** * @param treeList 数据 * @param parentIdValue 父级值 * @param parentIdFiled 父级字段名称 * @param idFiled 子级字段名称 * @Description json转jsonTree * @Author dongjd * @Date 19-1-11 下午5:38 * @Return com.alibaba.fastjson.JSONArray */ public static JSONArray jsonTreeFormat(List<Map<String, Object>> treeList, String parentIdValue, String parentIdFiled, String idFiled) { JSONArray childMenu = new JSONArray(); treeList.stream().map(map -> JSONObject.parseObject(JSON.toJSONString(map))).forEach(jsonMenu -> { String menuId = jsonMenu.getString(idFiled); String pid = jsonMenu.getString(parentIdFiled); if (parentIdValue.equals(pid)) { JSONArray childList = jsonTreeFormat(treeList, menuId, parentIdFiled, idFiled); jsonMenu.put("childList", childList); childMenu.add(jsonMenu); } }); return childMenu; }
参考资料[1]:https://blog.csdn.net/jianxia801/article/details/82771346
/**
* @param treeList 数据
* @param parentIdValue 父级值
* @param parentIdFiled 父级字段名称
* @param idFiled 子级字段名称
* @Description json转jsonTree
* @Author dongjd
* @Date 19-1-11 下午5:38
* @Return com.alibaba.fastjson.JSONArray
*/
public static JSONArray jsonTreeFormat(List<Map<String, Object>> treeList, String parentIdValue, String parentIdFiled, String idFiled) {
JSONArray childMenu = new JSONArray();
treeList.stream().map(map -> JSONObject.parseObject(JSON.toJSONString(map))).forEach(jsonMenu -> {
String menuId = jsonMenu.getString(idFiled);
String pid = jsonMenu.getString(parentIdFiled);
if (parentIdValue.equals(pid)) {
JSONArray childList = jsonTreeFormat(treeList, menuId, parentIdFiled, idFiled);
jsonMenu.put("childList", childList);
childMenu.add(jsonMenu);
}
});
return childMenu;
}