V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
mikulch
V2EX  ›  问与答

Java 如何反序列化一个自我引用的对象为 json 字符串?

  •  
  •   mikulch · 2020-12-04 18:57:46 +08:00 · 445 次点击
    这是一个创建于 1210 天前的主题,其中的信息可能已经有所发展或是发生改变。

    代码

           Category category = new Category();
            category.setName("test1");
            Category category2 = new Category();
            category2.setName("test2");
            category.setParent(category2);
            BrandCategoryDTO brandCategoryDTO1 = new BrandCategoryDTO(category);
            System.out.println(JSONObject.toJSONString(brandCategoryDTO1));
    
        public BrandCategoryDTO(Category category) {
            this.name = category.getName();
            this.id = category.getId();
            if (category.getParent() != null) {
                this.category = new BrandCategoryDTO(category.getParent());
            }
        }
    

    最后输出 {"name":"test1"}。预想的结果是将嵌套对象也输出出来。

    用 debug 可以明确看到嵌套对象是存在于 dto 对象之中的,但是不知道为什么反序列化成 json 就不行了。

    现在实际项目的情况是,把 dto 通过 spring boot 框架直接返回给前端以后,前端看不到里面的嵌套对象,很奇怪。

    mikulch
        1
    mikulch  
    OP
       2020-12-04 18:59:27 +08:00
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1126 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 22:55 · PVG 06:55 · LAX 15:55 · JFK 18:55
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.