mikulch
V2EX  ›  问与答

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

  •  
  •   mikulch · Dec 4, 2020 · 800 views
    This topic created in 1995 days ago, the information mentioned may be changed or developed.

    代码

           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
       Dec 4, 2020
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3109 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 06:23 · PVG 14:23 · LAX 23:23 · JFK 02:23
    ♥ Do have faith in what you're doing.