json對象出現$ref: "$.list[0]"的解決辦法


json對象出現$ref: "$.list[0]"的解決辦法

該問題被稱為 循環引用 (當一個對象包含另一個對象時,fastjson就會把該對象解析成引用)

{
  "content": [
    {
      "age": 18,
      "id": 3,
      "name": "three"
    },
    {
      "$ref": "$.content[0]"
    },
    {
      "$ref": "$.content[0]"
    }
  ],
  ...
}

首先了解一下為什么會出現以下這種情況?讓我們再看看后台的模擬代碼

    @PostMapping(value = "/student/list", produces = MediaType.APPLICATION_JSON_VALUE)
    public String studentList() {

        List<Student> studentList = new ArrayList<>();

        Student student = new Student();

        student.setId(1);
        student.setName("one");
        student.setAge(12);
        studentList.add(student);

        student.setId(2);
        student.setName("two");
        student.setAge(15);
        studentList.add(student);

        student.setId(3);
        student.setName("three");
        student.setAge(18);
        studentList.add(student);

        for (Student s : studentList) {
            System.out.println("student: " + s + "-hashCode: " + s.hashCode());
        }
        /* 打印結果:
        student: Student(id=3, name=three, age=18)-hashCode: 110556370
        student: Student(id=3, name=three, age=18)-hashCode: 110556370
        student: Student(id=3, name=three, age=18)-hashCode: 110556370
        */

        return JSON.toJSONString(studentList);
    }

看似我們向 studentList 列表中放入三個 student對象 ,但是由於他們的地址是同一個,普通的JSON.toJSONString()解析就會出問題!

如果想解決這個問題可以使用fastjson提供的枚舉類SerializerFeature的DisableCircularReferenceDetect轉換方案

String s = JSON.toJSONStringWithDateFormat(object,"yyyy-MM-dd HH:mm:ss",SerializerFeature.DisableCircularReferenceDetect);

只需要將上面的后台案例代碼改一下就OK了

 @PostMapping(value = "/student/list", produces = MediaType.APPLICATION_JSON_VALUE)
    public String studentList() {
 		... 中間代碼不變
        return JSON.toJSONStringWithDateFormat(studentList,"yyyy-MM-dd HH:mm:ss",SerializerFeature.DisableCircularReferenceDetect)
    }

再次測試接口,結果如下:

[
  {
    "age": 18,
    "id": 3,
    "name": "three"
  },
  {
    "age": 18,
    "id": 3,
    "name": "three"
  },
  {
    "age": 18,
    "id": 3,
    "name": "three"
  }
]

循環引用的問題得到解決。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM