问题描述:
当我们使用fastjson工具包的方法转换成字符串时,我们发现转换后的字符串不正确,出现了$ref,如图
为啥会出现$ref:
这是因为我们对象出现了重复引用,待转换的对象有不同内部变量指向了同一个对象。
public class User { private String userName; public User(String userName) { this.userName = userName; } // get与set方法省略 } public class Order { private User userA; private User userB; public Order(User userA, User userB) { super(); this.userA = userA; this.userB = userB; } // get与set方法省略 }
JSON字符串输出:
public class FastJsonTest { public static void main(String[] args) { User user = new User("张三"); Order order1 = new Order(user, user); System.out.println(JSON.toJSONString(order1)); } }
输出:
{"userA":{"userName":"张三"},"userB":{"$ref":"$.userA"}}
解决方式:
我们可以加上序列化参数:SerializerFeature.DisableCircularReferenceDetect
public class FastJsonTest { public static void main(String[] args) { User user = new User("张三"); Order order1 = new Order(user, user); System.out.println(JSON.toJSONString(order1, SerializerFeature.DisableCircularReferenceDetect)); } }
输出:
{"userA":{"userName":"张三"},"userB":{"userName":"张三"}}
思考:
如果出现了$ref一定我们对象构造上问题,我们更应该规范我们开发