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?
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;
Use this instead
builder.Services.Configure<Microsoft.AspNetCore.Http.Json.JsonOptions>(options =>
{
options.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
});
Minimal API
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With