arrow_back How to generate JSON?

1 vote
public class Department
public int Id { get; set; }
public string Name { get; set; }
public int Salary { get; set; }
public IEnumerable<Employee> Employees { get; set; }
public async Task<ActionResult<IEnumerable<Department>>> Get(int id)
var employees = db.Employees.Include(d => d.Department).Where(x => x.Department.Id == id);
var json = new Department
Id = id,
Name = db.Departments.FirstOrDefault(x => x.Id == id).Name,
Salary = (int)employees.Average(x => x.Salary),
Employees = employees
return new ObjectResult(json);
I try to insert a list into the Employees variable, but an error pops up when I access it
JsonException: A possible object cycle was detected which is not supported. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32.
Can you please tell me what's wrong?


freeExec It's true, there was a variable of the Department type, put [JsonIgnore] on it, it seems to have helped, thank you
recursion somewhere in Employees

1 Answer

0 votes
Most likely, your list does not contain the objects themselves, but references to them in the database. You need Select to get everything you need. You can also use NewtonSoft.Json