I have a mssql database for my website within 4 tables.
When I use this:
public static string GetAllEventsForJSON()
{
using (CyberDBDataContext d
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; }
}
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
for asp.net core 3.1.3 this worked for me
services.AddControllers().AddNewtonsoftJson(opt=>{
opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
JsonConvert.SerializeObject(ObjectName, new JsonSerializerSettings(){
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
Formatting = Formatting.Indented
});
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;
});