【问题标题】:C# return json result as an array which is not requiredC#将json结果作为不需要的数组返回
【发布时间】:2022-10-05 16:13:18
【问题描述】:

我正在为员工管理创建 .net core web api 应用程序,并且我已经使用控制器编写了 api。 我想通过 id 方法返回 json 对象而不是数组中的数据。

我的代码如下所示:

       [HttpGet(\"{id}\")]
    public JsonResult Get(int id)
    {
        string query = @\"select EmployeeId,EmployeeFirstName,EmployeeLastName,EmployeeEmail,EmployeeGender,(select DepartmentName from Department where DepartmentId =Employee.Emp_DepartmentId) as DepartmentName,(select DesignationName from Designation where DesignationId=Employee.Emp_DesignationId) as DesignationName,EmployeeDob from Employee where EmployeeId = @EmployeeId \";
        DataTable table = new DataTable();
        string sqlDataSource = _configuration.GetConnectionString(\"Dbconn\");
        SqlDataReader myReader;
        using (SqlConnection myCon = new SqlConnection(sqlDataSource))
        {
            myCon.Open();
            using (SqlCommand myCommand = new SqlCommand(query, myCon))
            {
                myCommand.Parameters.AddWithValue(\"@EmployeeId\", id);
                myReader = myCommand.ExecuteReader();
                table.Load(myReader);
                myReader.Close();
                myCon.Close();
            }
        }
        return new JsonResult(table);
    }

它的输出如下:

   [
    {
    \"EmployeeId\": 1,
    \"EmployeeFirstName\": \"abcd\",
    \"EmployeeLastName\": \"abcd\",
    \"EmployeeEmail\": \"abcd@abcd.com\",
    \"EmployeeGender\": \"abcd\",
    \"EmployeeDoj\": \"1995-01-01T00:00:00\",
    \"DepartmentName\": \"abcd\",
    \"DesignationName\": \"abcd\",
    \"EmployeeDob\": \"1995-01-01T00:00:00\"
    }
   ]

但我想要这样的输出:

{
\"EmployeeId\": 1,
\"EmployeeFirstName\": \"abcd\",
\"EmployeeLastName\": \"abcd\",
\"EmployeeEmail\": \"abcd@abcd.com\",
\"EmployeeGender\": \"abcd\",
\"EmployeeDoj\": \"1995-01-01T00:00:00\",
\"DepartmentName\": \"abcd\",
\"DesignationName\": \"abcd\",
\"EmployeeDob\": \"1995-01-01T00:00:00\"
}
  • 使用DataTables 可以做到这一点。最好将数据读入一个对象并返回它。可能使用 ORM,或者只是手动映射数据。
  • 返回表的第一行 (DataRow)。我最近使用过 DataSets/DataTables 和 JSON Web 服务,但我猜它应该可以工作(我已经有大约十年没有使用过 DataSets/DataTables 了。你会更喜欢真正的 ORM

标签: c# json .net asp.net-core-webapi


【解决方案1】:

在您的情况下,变量 table 代表您在数据库中的表。它是一个集合(数组),这就是 JSON 输出在 [] 大括号中的原因。您可能希望从表中获取第一个也是唯一的元素,然后将其作为 JSON 返回。

【讨论】:

    【解决方案2】:

    最简单的方法是将 DataTable 转换为对象数组并将第一个数组对象作为 json 返回

    using Newtonsoft.Json;
    
     return new JsonResult(JArray.FromObject(dt)[0]);
    

    【讨论】:

      【解决方案3】:

      我想通过 id 方法返回 json 对象中的数据而不是 大批。

      由于您使用的是datatable,所以无论您如何返回它都会在[] 数组中。但是,您可以在 Data Reader 上使用 while loop。您可以按照以下示例进行操作:

      使用 Ado.Net 数据阅读器:

              [HttpGet]
              public JsonResult GetSingleData(int id)
              {
                  var printer = new PrinterJob();
                  string query = " SELECT [PrinterId] ,[PrinterName],[PrintedBy],[TotalPrint] FROM [WsAttendance].[dbo].[PrintJob] WHERE PrinterId = @PrinterId";
                  string sqlDataSource = "Server=ServerName; Database=DatabaseName;Trusted_Connection=True;MultipleActiveResultSets=true";
                  SqlDataReader myReader;
                  using (SqlConnection myCon = new SqlConnection(sqlDataSource))
                  {
                      myCon.Open();
                      using (SqlCommand myCommand = new SqlCommand(query, myCon))
                      {
                          myCommand.Parameters.AddWithValue("@PrinterId", id);
                          myReader = myCommand.ExecuteReader();
                          while (myReader.Read())
                          {
      
                              printer.PrinterId = (int)myReader["PrinterId"]; // Remember Type Casting is required here it has to be according to database column data type
                              printer.PrinterName = myReader["PrinterName"].ToString();
                              printer.PrintedBy = (int)myReader["PrintedBy"];
                              printer.TotalPrint = (int)myReader["TotalPrint"];
      
                          }
                          myReader.Close();
                          myCon.Dispose();
                          myCon.Close();
                      }
                  }
                  return new JsonResult(printer);
              }
      

      笔记:您也可以使用Return ok(printer) 以及Json 数据。

      输出:

      【讨论】:

        猜你喜欢
        • 2017-03-09
        • 2017-02-17
        • 2014-07-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-13
        • 2013-04-09
        相关资源
        最近更新 更多