FastJson重复引用问题

前言

在使用fastJson转换对象时,出现了重复引用的问题。
导致生成的json字符串中,出现了$ref的字段。

问题描述

1.maven中引入fastJson的依赖

<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>2.0.51</version>
</dependency>

2.定义测试方法,复现问题

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

/**
 * @author JMY
 * @version 1.0
 * @date 2024/10/21 15:21
 * @content 细心仔细
 */
public class demo4 {
    public static void main(String[] args) {
        test1();
        test2();
    }
    public static void test1() {
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("value","value1");
        JSONObject jsonObject_w=new JSONObject();
        jsonObject_w.put("字段1",jsonObject);
        jsonObject_w.put("字段2",jsonObject);
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(jsonObject_w);
        System.out.println(jsonArray);
    }
    public static void test2() {
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("value","value1");
        JSONObject jsonObject2=new JSONObject();
        jsonObject2.put("value","value1");
        JSONObject jsonObject_w=new JSONObject();
        jsonObject_w.put("字段1",jsonObject);
        jsonObject_w.put("字段2",jsonObject2);
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(jsonObject_w);
        System.out.println("正常情况-"+jsonArray);
    }
}

3.运行结果
image.png
4.问题分析
通过对比发现,当两个对象引用的是同一个对象时,会出现重复引用的问题。

解决方法

1.使用fastJson的SerializerFeature.DisableCircularReferenceDetect参数,禁用循环引用检测。

JSONArray jsonArray = new JSONArray();
jsonArray.add(jsonObject_w);
System.out.println(JSON.toJSONString(jsonArray, SerializerFeature.DisableCircularReferenceDetect));

2.运行结果
image.png

其他标识情况

{"$ref": "$"} // 引用根对象
{"$ref":"@"} // 引用自己
{"$ref":".."} // 引用父对象
{"$ref":"../.."} // 引用父对象的父对象
{"$ref":"$.members[0].reportTo"} // 基于路径的引用