1

I have a Model with ICollection:

public class Blog
{
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    public ICollection<Posts> Posts { get; set; }
}

This works with MVC:

public async Task<IActionResult> Index()
{
    return View(await _context.Blog.Include(l => l.Posts).ToListAsync());
}

I try to use API-Controller:

[Route("api/[controller]")]
[ApiController]
....
[HttpGet]
public IEnumerable<Blog> GetAll()
{
    return _context.Blog.Include(l => l.Posts).ToList();
}

This generate a error:

SyntaxError: JSON.parse: end of data after property value in object at line 1 column 44 of the JSON data

How to return a multidimensional Json with Blogs and for every Blog entry all Posts?

0

2 Answers 2

2

Solution:

This is a error in JSON serialization.

Add in Startup.cs to Mvc ConfigureServices:

services.AddMvc()
            .AddJsonOptions(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
Sign up to request clarification or add additional context in comments.

Comments

0

Try this

[Route("api/[controller]")]
[ApiController]
 ....
[HttpGet]
public IActionResult GetAll()
{
   return Ok(_context.Blog.Include(l => l.Posts).ToList());
}

If you try async wrap IActionResult in Task

1 Comment

No, same problem "SyntaxError: JSON.parse: end of data after property value in object at line 1 column 44 of the JSON data" Return String is: [{"id":1,"name":"TestBlog","posts":[{"id":1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.