c# - 使用 Web Api 创建格式不正确的 Json 格式

标签 c# web-services asp.net-web-api

输出:

{
  "$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/

相关文章:

asp.net-web-api - 如何重命名 Web Api Bearer Token ".expires" key ?

c# - 如何构建批量返回数据的WCF服务

c# - ORM支持泛型映射

c# - 基于标签和地理位置的 Instagram 提要

java - 从 Web 服务获取多个响应

Android Facebook 登录和网络服务器

asp.net - 即使使用正确的 Accepts header ,WebAPI 也不返回 XML

c# - 双向 http 流式传输

C# 反射有帮助吗? (获取属性)

mysql - 与 mysql 和多个并发连接的写入后读取一致性