簡體   English   中英

在C#Newtonsoft中將DataTable序列化為JSON對象

[英]Serialize DataTable into JSON Object in C# Newtonsoft

我正在使用ASP.NET開發WEB API。 序列化數據表時我有點麻煩。 當我序列化DataTable時,它序列化為Json String。 但是我需要JSON對象或JSON ARRAY。

我的密碼

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

但它以JSON字符串形式返回。 我需要作為JSON對象。

“ [{\\” 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}]”

但是我需要像對象一樣序列化,

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

我對JSON序列化和反序列化感到有些困惑。

1)停止使用DataTable。 它們對於數據來說是一個糟糕的抽象。 使用強類型的對象。 達珀很方便。 它是可與任何ADO.NET數據提供程序一起使用的微型ORM。 您提供查詢,它將查詢結果映射到強類型對象(一個類)。 Dapper 在NuGet上可用。

2)您的操作方法不應返回IEnumerable 它應該返回IEnumerable<T>

3)您應該讓框架處理將對象轉換為JSON的過程,而不要自己做。 無需涉及JSON.NET。 如果從操作方法返回對象,則框架會將其轉換為JSON。

4)您沒有在一次性對象(SqlConnection)上正確使用IDisposable模式。 需要將它們包裝在using語句中,或將其處理在finally塊中。

5)您有兩個SqlConnection,只需要一個。

6)您應該利用存儲庫模式,而不是直接在控制器中進行數據訪問。 遵循關注點分離,為此負責一個單獨的類。

資料儲存庫

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

控制者

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

模型

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

    public string FirstName { get; set; }

    public int Salary { get; set; }
}

如果您不想使用Dapper,則可以手動處理命令的結果:

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM