>  기사  >  백엔드 개발  >  ASP.NET MVC에서 JSON 루프 호출 문제를 해결하는 방법은 무엇입니까?

ASP.NET MVC에서 JSON 루프 호출 문제를 해결하는 방법은 무엇입니까?

零下一度
零下一度원래의
2017-06-23 15:17:171967검색

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으로 문의하세요.