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());
        }
    }
}
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-05-25
  • 2022-12-23
  • 2021-11-07
  • 2022-12-23
  • 2021-09-19
猜你喜欢
  • 2022-12-23
  • 2021-10-20
  • 2021-07-05
  • 2021-06-29
相关资源
相似解决方案