Address the problem of FastJson circular references in springmvc


Let’s start with an example:

package com.elong.bms;

import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;

public class Test {
 public static void main(String[] args) {
 Map<String, Student> maps = new HashMap<String, Student>();
 Student s1 = new Student("s1", 16);

 maps.put("s1", s1);
 maps.put("s2", s1);

 byte[] bytes = JSON.toJSONBytes(maps);

 System.out.println(new String(bytes));
 }
}

Output:

{"s1":{"age":16,"name":"s1"},"s2":{"$ref":"$.s1"}}

As you can see, this json cannot be used if sent to the front end. Fortunately, FastJson provides a solution. Let’s take a look.

package com.elong.bms;

import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

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

public class Test {
 public static void main(String[] args) {
 Map<String, Student> maps = new HashMap<String, Student>();
 Student s1 = new Student("s1", 16);

 maps.put("s1", s1);
 maps.put("s2", s1);

 SerializerFeature feature = SerializerFeature.DisableCircularReferenceDetect;

 byte[] bytes = JSON.toJSONBytes(maps,feature);

 System.out.println(new String(bytes));
 }
}

The output is as follows:

{"s1":{"age":16,"name":"s1"},"s2":{"age":16,"name":"s1"}}

The problem is if we’re using spring mvc, we need to inject SerializerFeature into MessageConverter, FastJsonHttpMessageConverter

However, SerializerFeature is of type 1 enum and another array. Considering that most people are not familiar with this, we will go straight to the code.

<bean id="jsonConverter"
  class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
  <property name="supportedMediaTypes" value="application/json;charset=UTF-8"/>
  <property name="features">
  <array value-type="com.alibaba.fastjson.serializer.SerializerFeature">
   <value>DisableCircularReferenceDetect</value>
  </array>
  </property>
 </bean>
 <bean id="DisableCircularReferenceDetect" class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean">
  <property name="staticField" value="com.alibaba.fastjson.serializer.SerializerFeature.DisableCircularReferenceDetect"></property>
 </bean>