完整的工作控制台应用程序代码粘贴在下面。但是您需要的两种主要方法如下。
要使此代码正常工作,您必须在项目中执行以下操作。
- 将
JSON.Net
Nuget 包添加到项目中。
添加对System.Web.Extensions
(如果System.Web.Script.Serialization.JavaScriptSerializer
在方法中引用的行中出现编译错误)的引用GetJson
。
/// <summary>
/// Returns Json representation of Generic class with only matching properties from the DataTable (passed as parameter)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
public static string GetJsonFromDataTable<T>(DataTable dt) where T : new()
{
string json = GetJson(dt);
return JsonConvert.SerializeObject(JsonConvert.DeserializeObject<List<T>>(json));
}
/// <summary>
/// Returns a JSON string for entire DataTable (passed as parameter)
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static string GetJson(DataTable dt)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = (from DataRow dr in dt.Rows select dt.Columns.Cast<DataColumn>().ToDictionary(col => col.ColumnName.Trim(), col => dr[col])).ToList();
return serializer.Serialize(rows);
}
完全工作的控制台应用程序代码。
创建一个新的控制台应用程序,并Program.cs
用此代码替换其中的所有内容。还将 JSON.Net 添加到控制台应用程序项目并将引用添加到System.Web.Extensions
.
namespace DataTable2Json
{
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
public class Patient
{
public string FullName { get; set; }
public string PatientID { get; set; }
public int NumberOfIllnesses { get; set; }
public DateTime DateAdmitted { get; set; }
}
public class PatientDrug
{
public string Patient { get; set; }
public string Drug { get; set; }
}
internal class Program
{
private static void Main(string[] args)
{
DataTable patientDrugDataTable = GetPatientDrugTable();
DataTable patientDataTable = GetPatientTable();
string patientDrugJson = GetJsonFromDataTable<PatientDrug>(patientDrugDataTable);
Console.WriteLine("Json for PatientDrug:\n{0}",patientDrugJson);
string patientJson = GetJsonFromDataTable<Patient>(patientDataTable);
Console.WriteLine("\nJson for Patient:\n{0}", patientJson);
Console.WriteLine("\n\nPress a key to Exit...");
Console.ReadKey();
}
private static DataTable GetPatientDrugTable()
{
//
// Here we create a DataTable with four columns.
//
DataTable table = new DataTable();
table.Columns.Add("Dosage", typeof(int));
table.Columns.Add("Drug", typeof(string));
table.Columns.Add("Patient", typeof(string));
table.Columns.Add("Date", typeof(DateTime));
//
// Here we add five DataRows.
//
table.Rows.Add(25, "Indocin", "David", DateTime.Now);
table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
return table;
}
private static DataTable GetPatientTable()
{
//
// Here we create a DataTable with four columns.
//
DataTable table = new DataTable();
table.Columns.Add("NumberOfIllnesses", typeof(int));
table.Columns.Add("PatientID", typeof(string));
table.Columns.Add("FullName", typeof(string));
table.Columns.Add("DateAdmitted", typeof(DateTime));
table.Columns.Add("StreetAddress1", typeof(string));
table.Columns.Add("City", typeof(string));
table.Columns.Add("State", typeof(string));
//
// Here we add five DataRows.
//
table.Rows.Add(2, "PAT-00001", "David", DateTime.Now, "1 Mill Ln", "Schenectady", "NY");
table.Rows.Add(1, "PAT-00002", "Sam", DateTime.Now, "1915 Boylston Steet", "Boston", "MA");
table.Rows.Add(3, "PAT-00003", "Christoff", DateTime.Now, "15 Polk Steet", "San Francisco", "CA");
table.Rows.Add(4, "PAT-00004", "Janet", DateTime.Now, "10 Waverly St", "Los Angeles", "CA");
table.Rows.Add(5, "PAT-00005", "Melanie", DateTime.Now, "50 Kapaa St", "Kailua", "HI");
return table;
}
/// <summary>
/// Returns Json representation of Generic class with only matching properties from the DataTable (passed as parameter)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
public static string GetJsonFromDataTable<T>(DataTable dt) where T : new()
{
string json = GetJson(dt);
return JsonConvert.SerializeObject(JsonConvert.DeserializeObject<List<T>>(json));
}
/// <summary>
/// Returns a JSON string for entire DataTable (passed as parameter)
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static string GetJson(DataTable dt)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = (from DataRow dr in dt.Rows select dt.Columns.Cast<DataColumn>().ToDictionary(col => col.ColumnName.Trim(), col => dr[col])).ToList();
return serializer.Serialize(rows);
}
}
}
代码说明:
请注意,我有 2 个课程,Patient
并且PatientDrug
. 我编写了帮助方法来返回两个类的数据表,它们都有额外的列。然后以下 2 行分别获取 和 的类表示的 JSON Patient
,PatientDrug
同时忽略 DataTable 中与名称不匹配的其他数据列。
string patientDrugJson = GetJsonFromDataTable<PatientDrug>(patientDrugDataTable);
string patientJson = GetJsonFromDataTable<Patient>(patientDataTable);
控制台窗口中的输出(json 字符串)