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 jsonjsonTree
* @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;
}
posted @ 2019-01-14 16:47  膜拜曾文正  阅读(1730)  评论(0编辑  收藏  举报