Return in JSON

Asked

Viewed 51 times

0

You guys, a doubt.

Making an API on NET 5 and using EF, when I make a query for related data the return on JSON gives error 500.

// GET: api/Estadoes/5
    [HttpGet("{id}")]
    public async Task<List<Cidade>> GetCidade(int id)
    {
        var cidades = await _context.Cidades
                                    .Where(e => e.IdEstado == id)
                                    .Include(c => c.IdEstadoNavigation)
                                    .ToListAsync();

      
        return cidades;
    }

What is the correct way to convert this data to JSON?

  • If you returned a 500 it is probably because an exception was blown. In this case, the best way to help you is knowing what the exception was.

  • Error: Response body Download System.Text.Json.Jsonexception: A possible Object Cycle was Detected. This either can be due to a Cycle or if the Object Depth is Larger than the Maximum allowed Depth of 32. Consider using Referencehandler.Preserve on Jsonserializeroptions to support Cycles. at System.Text.Json.ThrowHelper.Throwjsonexception_serializercycledetected(Int32 maxDep

  • It is very likely that you have a circular reference in the EF templates. Try [Edit] your question and add the Dbset classes of Cidades and Estados. Tip: Remove the properties of "basic" types (int, long, string, etc.) and focus on relationships/navigations.

1 answer

0

  1. Check the version of Newtonsoft
  2. Try the code below:
services.AddControllersWithViews()
    .AddNewtonsoftJson(options =>
    options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.