序列化成Json时,多个对象互相引用导致死循环 Text.Json.JsonException: A possible object cycle was detected.
错误: 当两个类中的属性互相引用时,导致对象实例序列化成Json时死循环,错误如下:
System.Text.Json.JsonException: A possible object cycle was detected.
This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32.
Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles.
Path: $.Order.Delivery.Order.Delivery.Order.Delivery.Order.Delivery.Order.Delivery.Order.Delivery.Order.Delivery.Order.Delivery.Order.Delivery.Order.Delivery.Order.Delivery.Order.Delivery.Order.Delivery.Order.Delivery.Order.Delivery.Order.Id.
解决方法:
在 Program.cs中添加 AddJsonOptions 选项配置,此配置Json不但不会死循环而且还能完整表达实例之间的互相引用关系。
builder.Services.AddControllers() .AddJsonOptions(option => option.JsonSerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.Preserve);
增加AddJsonOptions 后的结果:
{ "$id": "1", "id": 1, "companyName": "蜗牛快递", "number": "SN356565565", "order": { "$id": "2", "id": 1, "name": "USB 充电器", "address": "湖南省长沙市岳阳临湘大市场", "delivery": { "$ref": "1" } }, "orderId": 1 }