输出:
{
"$id": "1",
"_MenuList": [
{
"$id": "2",
"parentId": 3,
"menuName": "Details"
},
{
"$id": "3",
"parentId": 1,
"menuName": "No of Details"
}
]
}
在输出“$id”中自动生成如何删除它。
格式代码 Controller :
[Route("MenuController/getMenuList/input")]
[HttpPost]
public ReportMenu getMenuList([FromBody]LoginModel input)
{
DataTable reportvalue = new DataTable();
try
{
using (SqlConnection dataConnection = ConnectionString.getConnection())
{
SqlCommand command = new SqlCommand("USP_ReportMenu", dataConnection);
command.Parameters.AddWithValue("@userName", input.userName);
command.Parameters.AddWithValue("@password", input.password);
command.CommandType = CommandType.StoredProcedure;
using (SqlDataAdapter reportAdapter = new SqlDataAdapter(command))
{
reportAdapter.Fill(reportvalue);
}
}
}
catch (SqlException ex)
{
}
return getJson(reportvalue);
}
public ReportMenu getJson(DataTable tb)
{
ReportMenu menu = new ReportMenu();
List<MenuModel> listMenu = new List<MenuModel>();
for (int i = 0; i < tb.Rows.Count; i++)
{
MenuModel obj=new MenuModel();
obj.parentId = Convert.ToInt16(tb.Rows[i]["parentId"].ToString());
obj.menuName = tb.Rows[i]["reportName"].ToString();
listMenu.Add(obj);
}
menu._MenuList = listMenu;
return menu;
}
我想要这种类型的输出:
{"_MenuList": [
{
"parentId": 3,
"menuName": "Details"
},
{
"parentId": 1,
"menuName": "No of Details"
}
]
}
请为我们提供帮助..我是 Web API 新手。
最佳答案
根据评论,您需要做的(根据我在评论中添加的文章)是替换:
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
这样:
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
这将忽略任何引用处理,但您将得到所需的结果。
关于c# - 使用 Web Api 创建格式不正确的 Json 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39448921/