[alibaba/fastjson]提一个复杂json序列化字符串的建议

2024-05-23 514 views
2
// 测试类
@Data
public class TestDemo {

    private String name;

    private Integer num;

    private Boolean isFlag;

    private List<TestDemo.Demo> demoList;

    private Map<String, List<TestDemo.Demo>> map;

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Demo {
        private String user;
        private String phone;
    }
}
public class JsonDemo {
    static TestDemo getDemo() {
        TestDemo demo = new TestDemo();
        demo.setName("测试");
        demo.setNum(1);
        demo.setIsFlag(true);
        List<TestDemo.Demo> demoList = new ArrayList<>();
        demoList.add(new TestDemo.Demo("张三", "15566667777"));
        demoList.add(new TestDemo.Demo("李四", "15577778888"));
        demoList.add(new TestDemo.Demo("王五", "15588889999"));
        demo.setDemoList(demoList);
        Map<String, List<TestDemo.Demo>> map = new HashMap<>();
        map.put("11", demoList);
        demo.setMap(map);
        return demo;
    }
    public static void main(String[] args) throws Exception {

        Object demo = getDemo();
        System.out.println(JSON.toJSONString(demo));
    }
}

程序运行,打印出的内容:

{"demoList":[{"phone":"15566667777","user":"张三"},{"phone":"15577778888","user":"李四"},{"phone":"15588889999","user":"王五"}],"isFlag":true,"map":{"11":[{"$ref":"$.demoList[0]"},{"$ref":"$.demoList[1]"},{"$ref":"$.demoList[2]"}]},"name":"测试","num":1}

期望: 希望Map的V能打印出正常的内容

备注: jdk版本:1.8 fastjson版本:1.2.68

回答

7

1.循环引用检测特性防止栈溢出,可以关闭 2.JSON.DEFAULT_GENERATE_FEATURE = JSON.DEFAULT_GENERATE_FEATURE | SerializerFeature.DisableCircularReferenceDetect.getMask(); 3.这个结合AfterFilter使用会有bug,参见 #3150 @wenshao

8

循环引用和重复引用的设置能否分开,有的场景需要重复引用的,但是循环引用又不能放开

2

@buzilong 嗯,赞同。?