简体   繁体   中英

Serialize DataTable into JSON Object in C# Newtonsoft

I am Developing WEB API using ASP.NET. I have little bit trouble while serializing the datatable. When I serialize the DataTable it serialized as a Json String. But I need either JSON Object or JSON ARRAY.

My code

[ActionName("EMPID")]
public System.Collections.IEnumerable Get()
{
    SqlConnection myConnection = new SqlConnection();
    string connString = ConfigurationManager
                          .ConnectionStrings["DefaultConnection"]
                          .ConnectionString;

    myConnection.ConnectionString = connString;
    DataTable dataTable = new DataTable();

    string query = "select EMPLOYEE_ID,FIRST_NAME,SALARY from Employee ";

    SqlConnection conn = new SqlConnection(connString);
    SqlCommand cmd = new SqlCommand(query, conn);
    conn.Open();
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    da.Fill(dataTable);

    var JSONString = JsonConvert.SerializeObject(dataTable);
    return JSONString;
}

public class Employee
{
    public int EmployeeId { get; set; }
    public string Name { get; set; }
    public int ManagerId { get; set; }
}

But it returns as JSON String. I need as a JSON Object.

Example

"[{\\"EMPLOYEE_ID\\":2,\\"FIRST_NAME\\":\\"Michael\\",\\"SALARY\\":800000},{\\"EMPLOYEE_ID\\":3,\\"FIRST_NAME\\":\\"Roy\\",\\"SALARY\\":700000},{\\"EMPLOYEE_ID\\":4,\\"FIRST_NAME\\":\\"Tom\\",\\"SALARY\\":600000},{\\"EMPLOYEE_ID\\":5,\\"FIRST_NAME\\":\\"Jerry\\",\\"SALARY\\":650000},{\\"EMPLOYEE_ID\\":6,\\"FIRST_NAME\\":\\"Philip\\",\\"SALARY\\":7500000},{\\"EMPLOYEE_ID\\":7,\\"FIRST_NAME\\":\\"Sachin\\",\\"SALARY\\":1100000},{\\"EMPLOYEE_ID\\":8,\\"FIRST_NAME\\":\\"Anshu\\",\\"SALARY\\":1200000},{\\"EMPLOYEE_ID\\":9,\\"FIRST_NAME\\":\\"Ravish\\",\\"SALARY\\":1000000}]"

But I need to Serialize as Object Like,

{"name":"Manas","gender":"Male","birthday":"1987-8-8"}

I am little bit confused with JSON Serialization & Deserialization.

1) Stop working with DataTable. They're a poor abstraction for the data. Use strongly typed objects. Dapper is handy for this. It is a micro-ORM that works with any ADO.NET data provider. You provide the query, and it will map the results of the query to a strongly typed object (a class). Dapper is available on NuGet .

2) Your action method shouldn't return an IEnumerable . It should return an IEnumerable<T>

3) You should let the framework handle converting your objects to JSON, don't do it yourself. There's no need to involve JSON.NET. If you return your object from your action method, the framework will convert it to JSON for you.

4) You are not using the IDisposable pattern correctly on your disposable objects (SqlConnection). They need to be wrapped in a using statement or disposed of in a finally block.

5) You have two SqlConnection's and only need one.

6) You should utilize the repository pattern instead of doing data access directly in your controller. Follow separation of concerns, have a separate class responsible for this.

Data Repository

using Dapper; //add this to your using statements

public class EmployeeRepository
{
    private readonly string _connectionString;

    public EmployeeRepository(string connectionString)
    {
        _connectionString = connectionString;
    }

    public List<Employee> GetAllEmployees()
    {
        string query = "select EMPLOYEE_ID, FIRST_NAME, SALARY from Employee";

        using (SqlConnection connection = new SqlConnection(_connectionString))
        {
            // Query is an extension method from Dapper
            List<Employee> employees = connection.Query<Employee>(query).AsList();
            return employees;
        }
    }
}

Controller

public class EmployeeController
{
    private readonly EmployeeRepository _employeeRepository;

    public EmployeeController()
    {
        string connString = ConfigurationManager
                                .ConnectionStrings["DefaultConnection"]
                                .ConnectionString;

        _employeeRepository = new EmployeeRepository(connString);
    }

    [ActionName("EMPID")] //why does this say EMPID?
    public IEnumerable<Employee> Get()
    {            
        List<Employee> employees = _employeeRepository.GetAllEmployees();
        return employees;      
    }
}

Model

public class Employee
{
    public int EmployeeId { get; set; }

    public string FirstName { get; set; }

    public int Salary { get; set; }
}

If you didn't want to use Dapper, you can manually processes the results of your command:

var employees = new List<Employee>();

using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand("select EMPLOYEE_ID, FIRST_NAME, SALARY from Employee", connection))
{
    connection.Open();

    using(var reader = command.ExecuteReader())
    {
        while (reader.Read())
        {
            Employee employee = new Employee();
            employee.EmployeeId = reader.GetInt32(reader.GetOrdinal("EMPLOYEE_ID"));
            employee.FirstName = reader.GetString(reader.GetOrdinal("FIRST_NAME"));
            employee.Salary = reader.GetInt32(reader.GetOrdinal("SALARY"));
            employees.Add(employee);
        }
    }
}

return employees;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM