1..Net开源Json系列化工具牛顿soft.Json中提供了缓解种类化的循环引用难点:

艺术1:指定Json连串化配置为 ReferenceLoopHandling.Ignore

方法2:指定 JsonIgnore忽略 引用对象

实例1,解决MVC的Json体系化引用方法:

step1:在品种上加上引用 牛顿soft.Json程序包,命令:Insert-Package
牛顿soft.Json

step2:在项目中添加一个类,继承JsonResult,代码如下:

json 1

json 2

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

json 3

step3:在类型添加BaseController,重写Json()方法,代码如下:

json 4

json 5

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
        };
    }
}

json 6

step4.向日常一模一样使用就可以了

json 7

json 8

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

json 9

取得的结果,表达,这种方法指定忽略循环引用,是在指定循环级数后忽略,再次回到的json数据中仍旧有一部分循环的多寡

json 10

解决EF Json种类化循环引用方法2,在指定的关联对象上,添加JsonIgnore
方法注释

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

回到结果中,没有关联表数据

json 11

文章转发自:http://www.cnblogs.com/tianma3798/p/5596703.html

相关文章

网站地图xml地图