Json.net对于导航属性的处理(解决对象循环引用)

对于两张表A、B多对多的关系中,A的导航属性中有B,B的导航属性中有A,这样Json.net对A或者B对象序列化时会形成死循环

所以对于导航属性要加标签

首先在A、B实体类工程(Model)中引用Json.ne

然后对导航属性加不序列化标签([JsonIgnore])

//------------------------------------------------------------------------------
// <auto-generated>
//    此代码是根据模板生成的。
//
//    手动更改此文件可能会导致应用程序中发生异常行为。
//    如果重新生成代码,则将覆盖对此文件的手动更改。
// </auto-generated>
//------------------------------------------------------------------------------

namespace CZBK.ItcastOA.Model
{
    using System;
    using System.Collections.Generic;
    using Newtonsoft.Json;
    public partial class UserInfo
    {
        public UserInfo()
        {
            this.R_UserInfo_ActionInfo = new HashSet<R_UserInfo_ActionInfo>();
            this.Department = new HashSet<Department>();
            this.RoleInfo = new HashSet<RoleInfo>();
        }
    
        public int ID { get; set; }
        public string UName { get; set; }
        public string UPwd { get; set; }
        public System.DateTime SubTime { get; set; }
        public short DelFlag { get; set; }
        public System.DateTime ModifiedOn { get; set; }
        public string Remark { get; set; }
        public string Sort { get; set; }
    
        [JsonIgnore]
        public virtual ICollection<R_UserInfo_ActionInfo> R_UserInfo_ActionInfo { get; set; }
                [JsonIgnore]
        public virtual ICollection<Department> Department { get; set; }
                [JsonIgnore]
        public virtual ICollection<RoleInfo> RoleInfo { get; set; }
    }
}

但需要把引用以及

[JsonIgnore]
        public virtual ICollection<R_UserInfo_ActionInfo> R_UserInfo_ActionInfo { get; set; }
                [JsonIgnore]
        public virtual ICollection<Department> Department { get; set; }
                [JsonIgnore]
        public virtual ICollection<RoleInfo> RoleInfo { get; set; }

加入T4 模板中。

这样在应用反序列化时,无法拿到导航属性,只能再次查找数据库!

----------------------------------------------------------------------------------------------

如果用微软自带的序列化解决办法

序列化类型为xxx的对象时检测到循环引用解决方法

方法一:关闭导航功能(不能再使用导航属性)

public ActionResult Index()
{
    testContext context = new testContext();
    context.Configuration.ProxyCreationEnabled = false;
    var data = context.People;
    return Json(data, JsonRequestBehavior.AllowGet);
}

方法二:转为匿名对象

public ActionResult Index()
{
    testContext context = new testContext();
    var data = context.People.Select(item => new { item.Id, item.Name });
    return Json(data, JsonRequestBehavior.AllowGet);
}

Newtonsoft.Json高级用法

原文地址:https://www.cnblogs.com/ecollab/p/6159914.html