IT

JSON.Net 자체 참조 루프 감지

lottoking 2020. 8. 31. 08:04
반응형

JSON.Net 자체 참조 루프 감지


4 개의 유전자 데이터베이스가 있습니다.

이것을 사용할 때 :

public static string GetAllEventsForJSON()
{
    using (CyberDBDataContext db = new CyberDBDataContext())
    {
        return JsonConvert.SerializeObject((from a in db.Events where a.Active select a).ToList(), new JavaScriptDateTimeConverter());
    }
}

이 코드는 다음 오류를 발생하고 있습니다.

Newtonsoft.Json.JsonSerializationException : 'DAL.CyberUser'유형의 'CyberUser'속성에 대해 자체 참조 루프가 감지되었습니다. 경로 '[0] .EventRegistrations [0] .CyberUser.UserLogs [0]'.


부모 / 마법 컬렉션에 대해 동일한 문제가 발생했습니다. 부모 컬렉션 항목 목록 만 표시하고 싶었습니다.

JsonConvert.SerializeObject(ResultGroups, Formatting.None,
                        new JsonSerializerSettings()
                        { 
                            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                        });

JSON.NET 자체 참조 루프가 유형에 대해 사용되었습니다.

또한 다음 위치의 Json.NET codeplex 페이지를 참조합니다.

http://json.codeplex.com/discussions/272371

문서 : ReferenceLoopHandling 설정


수정 사항은 루프 참조를 무시하고 가상화하지 않는 것입니다. 이 동작은 JsonSerializerSettings.

JsonConvert보강가있는 싱글 :

JsonConvert.SerializeObject((from a in db.Events where a.Active select a).ToList(), Formatting.Indented,
    new JsonSerializerSettings() {
        ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
    }
);

관리자 기본 동작으로 만들려면 Global.asax.cs에 코드가 있는 전역 설정추가합니다 Application_Start().

JsonConvert.DefaultSettings = () => new JsonSerializerSettings {
     Formatting = Newtonsoft.Json.Formatting.Indented,
     ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};

참조 : https://github.com/JamesNK/Newtonsoft.Json/issues/78


ASP.NET Core MVC를 사용하는 경우 다음을 startup.cs 파일의 ConfigureServices 메서드에 추가합니다.

services.AddMvc()
    .AddJsonOptions(
        options => options.SerializerSettings.ReferenceLoopHandling =            
        Newtonsoft.Json.ReferenceLoopHandling.Ignore
    );

이 당신을 도울 수 있습니다.

public MyContext() : base("name=MyContext") 
{ 
    Database.SetInitializer(new MyContextDataInitializer()); 
    this.Configuration.LazyLoadingEnabled = false; 
    this.Configuration.ProxyCreationEnabled = false; 
} 

http://code.msdn.microsoft.com/Loop-Reference-handling-in-caaffaf7


객체 참조 보존을 설정해야합니다.

var jsonSerializerSettings = new JsonSerializerSettings
{
    PreserveReferencesHandling = PreserveReferencesHandling.Objects
};

그런 다음 쿼리를 다음 var q = (from a in db.Events where a.Active select a).ToList();과 같이 호출하십시오.

string jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(q, jsonSerializerSettings);

참조 : https://www.newtonsoft.com/json/help/html/PreserveObjectReferences.htm


모델 클래스에 "[JsonIgnore]"추가

{
  public Customer()
  {
    Orders = new Collection<Order>();
  }

public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }

[JsonIgnore]
public ICollection<Order> Orders { get; set; }
}

JsonConvert.SerializeObject(ObjectName, new JsonSerializerSettings(){ PreserveReferencesHandling = PreserveReferencesHandling.Objects, Formatting = Formatting.Indented });

참고 URL : https://stackoverflow.com/questions/13510204/json-net-self-referencing-loop-detected

반응형