Home > OS >  C# return json result as an array which is not required
C# return json result as an array which is not required

Time:10-04

I am creating .net core web api application for employee management and i have written api using controller. I want get by id method to return data in json object and not in array.

My code looks like this :

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

And its giving output like this :

   [
    {
    "EmployeeId": 1,
    "EmployeeFirstName": "abcd",
    "EmployeeLastName": "abcd",
    "EmployeeEmail": "[email protected]",
    "EmployeeGender": "abcd",
    "EmployeeDoj": "1995-01-01T00:00:00",
    "DepartmentName": "abcd",
    "DesignationName": "abcd",
    "EmployeeDob": "1995-01-01T00:00:00"
    }
   ]

but i want output like this :

{
"EmployeeId": 1,
"EmployeeFirstName": "abcd",
"EmployeeLastName": "abcd",
"EmployeeEmail": "[email protected]",
"EmployeeGender": "abcd",
"EmployeeDoj": "1995-01-01T00:00:00",
"DepartmentName": "abcd",
"DesignationName": "abcd",
"EmployeeDob": "1995-01-01T00:00:00"
}

CodePudding user response:

In your case the variable table represents your table in database. It's a collection (array), that's why the JSON output is in [] braces. You probably want to get the first and only element from the table and then return that as a JSON.

CodePudding user response:

The easiest way would be convert DataTable to array of objects and return the first array object as json

using Newtonsoft.Json;

 return new JsonResult(JArray.FromObject(dt)[0]);
  • Related