'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?
Solution 1:[1]
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;
Solution 2:[2]
Use this instead
builder.Services.Configure<Microsoft.AspNetCore.Http.Json.JsonOptions>(options =>
{
options.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
});
Minimal API
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | mj1313 |
Solution 2 | Kenlly Acosta |