FastJson中循环引用的问题

问题场景
在公司代码中要传一个复合对象的list集合。在复合对象中的结构是,一个对象引用了另外一个对象。这时候,在Fastjson转化为json字符串的时候出现了问题,源代码改过了,所以这里描述一下。有A类,下A类中引用了B类。在A类查询都B的id,然后根据B的id再次在数据库中进行查询。因为测试服中A中的所有ID都是相同的,所以导致查询出来的B的结果是一样的。其中的代码如下。
if (invoices.getCompanyId() !=null) {
        EnterpriseCompany enterpriseCompany = new EnterpriseCompany();
        enterpriseCompany = enterpriseCompanyMapper.selectByPrimaryKey(invoices.getCompanyId());
        list.add(enterpriseCompany);
    }
在这样的情景下,fastJson会正确解析list中的第一个对象,如果A中引用的值和第一个相同的时候,就会出现问题,具体的内容就不能重现了。
会出现$ref的情况
“$ref”:”..” 上一级
“$ref”:”@” 当前对象,也就是自引用
“$ref”:”$” 根对象
“$ref”:”$.children.0” 基于路径的引用,相当于root.getChildren().get(0)
解决方案一
JSON.toJSONString(imList,SerializerFeature.DisableCircularReferenceDetect);
解决方案二
在代码中拒绝使用复杂对象,在代码中使用List<Map>这样的结构去组装数据,这样我感觉才是正确的打开方式。
List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
List<Map<String, Object>> listCompanys = enterpriseCompanyMapper.selectByParam(map);
            if (listCompanys.size() ==1) {
                Integer id = (Integer) listCompanys.get(0).get("id");
                String name = (String) listCompanys.get(0).get("name");
                map.put("companyId",id);
                List<EnterpriseAccountInvoices> invoicesList =enterpriseAccountInvoicesMapper.getInvoicesListByPage(map);
                if (invoicesList.size() > 0) {
                    for (EnterpriseAccountInvoices invoices : invoicesList) {
                        Map<String,Object> objectMap =new HashMap<String, Object>(0);
                        invoices.setDoubleInvoiceMoney(df.format(invoices.getInvoiceMoney() / 100.00));
                        invoices.setDoubleTaxesMoney(df.format(invoices.getTaxesMoney() / 100.00));
                        invoices.setTotalMoney(df.format((invoices.getInvoiceMoney() + invoices.getTaxesMoney()) / 100.00));
                        objectMap.put("invoices",invoices);
                        objectMap.put("companyName",name);
                        list.add(objectMap);
                    }
                }
            }

这样的话,想怎么封装数据就封装数据。

猜你喜欢

转载自blog.csdn.net/qq_25484147/article/details/80704160
今日推荐