使用WebApi创建Json格式,而不是属性格式

本文关键字:格式 属性 创建 Json 使用 WebApi | 更新日期: 2023-09-27 18:06:48

输出:

{
  "$id": "1",
  "_MenuList": [
    {
      "$id": "2",
      "parentId": 3,
      "menuName": "Details"
    },
    {
      "$id": "3",
      "parentId": 1,
      "menuName": "No of Details"
    }
  ]
}

在输出"$id"中自动生成如何删除这个

格式码控制器:

 [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;
    }

I want To this Type of output:

{"_MenuList": [
    {
      "parentId": 3,
      "menuName": "Details"
    },
    {
      "parentId": 1,
      "menuName": "No of Details"
    }
  ]
}

请帮助我们…I am new in Web API.

使用WebApi创建Json格式,而不是属性格式

根据评论,您需要做的(根据我在评论中添加的文章)是替换:

json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
与这个:

json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

这将忽略任何引用处理,但您将获得所需的结果。