JSON.Net Self referencing loop detected

前端 未结 11 726
伪装坚强ぢ
伪装坚强ぢ 2020-11-28 04:18

I have a mssql database for my website within 4 tables.

When I use this:

public static string GetAllEventsForJSON()
{
    using (CyberDBDataContext d         


        
相关标签:
11条回答
  • 2020-11-28 05:02

    Add "[JsonIgnore]" to your model class

    {
      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; }
    }
    
    0 讨论(0)
  • 2020-11-28 05:06

    You must set Preserving Object References:

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

    Then call your query var q = (from a in db.Events where a.Active select a).ToList(); like

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

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

    0 讨论(0)
  • 2020-11-28 05:06

    for asp.net core 3.1.3 this worked for me

    services.AddControllers().AddNewtonsoftJson(opt=>{
                opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            });
    
    0 讨论(0)
  • 2020-11-28 05:06

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

    0 讨论(0)
  • 2020-11-28 05:09

    I am using Dot.Net Core 3.1 and did an search for

    "Newtonsoft.Json.JsonSerializationException: Self referencing loop detected for property "

    I am adding this to this question, as it will be an easy reference. You should use the following in the Startup.cs file:

     services.AddControllers()
                    .AddNewtonsoftJson(options =>
                    {
                        // Use the default property (Pascal) casing
                        options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                        options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                    });
    
    0 讨论(0)
提交回复
热议问题