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));
}
}
输出
{"s1":{"age":16,"name":"s1"},"s2":{"$ref":"$.s1"}}
可以看到,这个json如果发到前端是无法使用的,幸好FastJson提供了解决办法,我们来看下,解决办法为禁用循环引用检测,代码如下:
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));
}
}
{"s1":{"age":16,"name":"s1"},"s2":{"age":16,"name":"s1"}}
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));
}
}
输出
{"s1":{"age":16,"name":"s1"},"s2":{"$ref":"$.s1"}}
可以看到,这个json如果发到前端是无法使用的,幸好FastJson提供了解决办法,我们来看下,解决办法为禁用循环引用检测,代码如下:
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));
}
}
{"s1":{"age":16,"name":"s1"},"s2":{"age":16,"name":"s1"}}