首頁 >後端開發 >C#.Net教程 >ASP.NET MVC 遇到JSON循環呼叫的問題該怎麼解決?

ASP.NET MVC 遇到JSON循環呼叫的問題該怎麼解決?

零下一度
零下一度原創
2017-06-23 15:17:172110瀏覽

1..Net開源Json序列化工具Newtonsoft.Json中提供了解決序列化的循環引用問題:

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

#方式2:指定JsonIgnore忽略引用物件

##實例1,解決MVC的Json序列化參考方法:

step1:在專案上新增引用Newtonsoft.Json程式包,指令:Insert-Package Newtonsoft.Json

#step2:在專案中加入一個類,繼承JsonResult,程式碼如下:

ASP.NET MVC 遇到JSON循環呼叫的問題該怎麼解決?#
/// <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());
        }
    }
}
ASP.NET MVC 遇到JSON循環呼叫的問題該怎麼解決?
#step3:在專案中加入BaseController,重寫Json()方法,程式碼如下:

ASP.NET MVC 遇到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
        };
    }
}
ASP.NET MVC 遇到JSON循環呼叫的問題該怎麼解決?
step4.往平常一樣使用就可以了

ASP.NET MVC 遇到JSON循環呼叫的問題該怎麼解決?#
//获取列表public JsonResult GetList()
{
    List<student> list = _Context.students.Where(q => q.sno == "103").ToList();//方法1return Json(list);//方法2//return new JsonNetResult() {//    Data=list//};
}</student>
ASP.NET MVC 遇到JSON循環呼叫的問題該怎麼解決?

所取得的結果,說明,這種方式指定忽略循環引用,是在指定循環級數後忽略,返回的json資料中還是有部分循環的資料


解決EF Json序列化循環參考方法2,在指定的關聯物件上,新增JsonIgnore 方法註解

#
[JsonIgnore]public virtual ICollection<score> scores { get; set; }</score>
#########傳回結果中,沒有關聯表資料###########################文章轉載自:# ########

以上是ASP.NET MVC 遇到JSON循環呼叫的問題該怎麼解決?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn