记一次JSON循环依赖的经历

Posted nguyenvm

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了记一次JSON循环依赖的经历相关的知识,希望对你有一定的参考价值。

笔者是从配置文件中读取JSON数组数据,类Metadata.class的结构如下:

技术分享图片
public class Metadata {
    public String id;

    public String codeNo;

    public String codeName;

    public String parentNo;

    public String description;

    public String state;

    public List<Metadata> subordinates;

}
View Code

JSON数据文件menu.json内容:

技术分享图片
[
  {
    "codeNo": "01",
    "codeName": "系统设置",
    "description": "系统设置模块",
    "metaState": "01",
    "parentNo": "",
    "subordinates": [
      {
        "codeNo": "0101",
        "codeName": "角色管理",
        "description": "角色管理菜单",
        "metaState": "01",
        "parentNo": "01",
        "subordinates": []
      },
      {
        "codeNo": "0102",
        "codeName": "账号管理",
        "description": "账号管理菜单",
        "metaState": "01",
        "parentNo": "01",
        "subordinates": []
      }
    ]
  },
  {
    "codeNo": "02",
    "codeName": "用户管理",
    "description": "用户管理模块",
    "metaState": "01",
    "parentNo": "",
    "subordinates": [
      {
        "codeNo": "0201",
        "codeName": "论坛用户",
        "description": "论坛用户菜单",
        "metaState": "01",
        "parentNo": "02",
        "subordinates": []
      }
    ]
  },
  {
    "codeNo": "03",
    "codeName": "社区管理",
    "description": "内容管理模块",
    "metaState": "01",
    "parentNo": "",
    "subordinates": [
      {
        "codeNo": "0301",
        "codeName": "帖子管理",
        "description": "帖子管理菜单",
        "metaState": "01",
        "parentNo": "03",
        "subordinates": []
      },
      {
        "codeNo": "0302",
        "codeName": "版块管理",
        "description": "版块管理菜单",
        "metaState": "01",
        "parentNo": "03",
        "subordinates": []
      }
    ]
  }
]
View Code

下面重点来了,分别采用两种方式读取:

/** 方式一:菜单列表 **/
    public static final List<Metadata> menuList() {
        return MENU_LIST;
    }
    private static List<Metadata> MENU_LIST;

    static {
        InputStream is = null;
        try {
            is = new ClassPathResource("/menu.json").getInputStream();
            MENU_LIST = JsonUtils.parseArray(ByteUtils.string(is), Metadata.class);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            is.close();
        }
    }
/** 方式二:菜单列表 **/
    public static List<Metadata> menuList() {
        InputStream is = null;
        List<Metadata> menus = null;
        try {
            is = new ClassPathResource("/menu.json").getInputStream();
            menus = JsonUtils.parseArray(ByteUtils.string(is), Metadata.class);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            is.close();
        }
        return menus;
    }

两种当时产生的数据返回给前端时,第一种会产生循环依赖,而第二种则不会!希望在你们的评论中得到答案?

以上是关于记一次JSON循环依赖的经历的主要内容,如果未能解决你的问题,请参考以下文章

记一次循环依赖踩坑

记一次node爬虫经历,手把手教你爬虫

记一次spring boot项目启动时的依赖循环

记一次阿里电面经历

记一次服务器密钥失效经历

记一次网站被黑经历