ASP.NET MVC 遇到JSON迴圈調用的問題應該怎麼解決?

來源:互聯網
上載者:User
1..Net開源Json序列化工具Newtonsoft.Json中提供瞭解決序列化的循環參考問題:

方式1:指定Json序列化配置為 ReferenceLoopHandling.Ignore

方式2:指定 JsonIgnore忽略 引用對象

執行個體1,解決MVC的Json序列化引用方法:

step1:在項目上添加引用 Newtonsoft.Json程式包,命令:Insert-Package Newtonsoft.Json

step2:在項目中添加一個類,繼承JsonResult,代碼如下:

/// <summary>/// 繼承JsonResut,重寫序列化方式/// </summary>public class JsonNetResult : JsonResult{public JsonSerializerSettings Settings { get; private set; }public JsonNetResult()    {        Settings = new JsonSerializerSettings        {//這句是解決問題的關鍵,也就是json.net官方給出的解決配置選項.                             ReferenceLoopHandling = ReferenceLoopHandling.Ignore        };    }public override void ExecuteResult(ControllerContext context)    {if (context == null)throw new ArgumentNullException("context");if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))throw new InvalidOperationException("JSON GET is not allowed");        HttpResponseBase response = context.HttpContext.Response;        response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;if (this.ContentEncoding != null)            response.ContentEncoding = this.ContentEncoding;if (this.Data == null)return;var scriptSerializer = JsonSerializer.Create(this.Settings);using (var sw = new StringWriter())        {            scriptSerializer.Serialize(sw, this.Data);            response.Write(sw.ToString());        }    }}

step3:在項目添加BaseController,重寫Json()方法,代碼如下:

public class BaseController : Controller{public StudentContext _Context = new StudentContext();/// <summary>/// 重寫,Json方法,使之返回JsonNetResult類型/// </summary>protected override JsonResult Json(object data, string contentType,        Encoding contentEncoding, JsonRequestBehavior behavior)    {return new JsonNetResult        {            Data = data,            ContentType = contentType,            ContentEncoding = contentEncoding,            JsonRequestBehavior = behavior        };    }}

step4.向平時一樣使用就可以了

//擷取列表public JsonResult GetList(){    List<student> list = _Context.students.Where(q => q.sno == "103").ToList();//方法1return Json(list);//方法2//return new JsonNetResult() {//    Data=list//};}

擷取的結果,說明,這種方式指定忽略循環參考,是在指定迴圈級數後忽略,返回的json資料中還是有部分迴圈的資料

解決EF Json序列化循環參考方法2,在指定的關聯對象上,添加JsonIgnore 方法注釋

[JsonIgnore]public virtual ICollection<score> scores { get; set; }

返回結果中,沒有關聯表資料


文章轉載自:

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.