Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core 5 returning JSON adding $id and $values properties

I'm using ASP.NET Core 5. As below, I'm using System.Text.Json:

public IActionResult Index()
{
   var result = GetAllMenuItems(); 
   return Ok(result);
}

The expected shape of my JSON is:

[
    {
        "NameEn": "omlet en",
        "MenuId": 258,
        "Categories": [
            {
                "MenuCategoryEn": "Lunch En",
                "Id": 175
            },
            {
                "MenuCategoryEn": "Dinner En",
                "Id": 176
            }
        ],
        "Id": 213
    }
]

But it is generating $id with random number and wrapping an actual data within $value:

{
  $id: "1",
  $values: [
    {
      $id: "2",
      nameEn: "omlet en",
      menuId: 258,
      categories: {
        $id: "3",
        $values: [
          {
            $id: "4",
            menuCategoryEn: "Lunch En",
            id: 175
          },
          {
            $id: "6",
            menuCategoryEn: "Dinner En",
            id: 176
          }
        ]
      },
      id: 213
    }
  ]
}

Classes are as follow and contains many to many navigation properties

public class MenuItem : BaseEntity
{
    public string NameEn { get; set; }
    public long MenuId { get; set; }
    public List<MenuCategory> Categories { get; set; } = new();
    public Menu Menu { get; set; }
}
public partial class MenuCategory : BaseEntity
{
    public string MenuCategoryEn { get; set; }
    public List<MenuItem> MenuItems { get; set; } = new();
}

Is there any proper solution to fix this?

like image 710
Uttam Ughareja Avatar asked Mar 06 '26 11:03

Uttam Ughareja


2 Answers

Do you configure the JsonOptions in stratup like below?

options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve;

Don't set ReferenceHandler as Preserve if you did that.

options.JsonSerializerOptions.ReferenceHandler = null;
like image 65
mj1313 Avatar answered Mar 08 '26 23:03

mj1313


Use this instead

builder.Services.Configure<Microsoft.AspNetCore.Http.Json.JsonOptions>(options =>
{
    options.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
});

Minimal API

like image 43
Kenlly Acosta Avatar answered Mar 09 '26 01:03

Kenlly Acosta