如何将DataTable序列化为json或xml

时间:2010-03-16 23:12:16

标签: c# .net serialization ado.net datatable

我正在尝试将DataTable序列化为Json或XML。可能吗?怎么样?请给我任何教程和想法。

例如a有一个sql表:

CREATE TABLE [dbo].[dictTable](
    [keyValue] [int] IDENTITY(1,1) NOT NULL,
    [valueValue] [int] NULL,
 CONSTRAINT [Psd2Id] PRIMARY KEY CLUSTERED 
(
    [keyValue] ASC
)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

C#代码:

string connectionString =
          "server=localhost;database=dbd;uid=**;pwd=**";

            SqlConnection mySqlConnection = new SqlConnection(connectionString);
            string selectString =  "SELECT keyValue, valueValue FROM dicTable";

            SqlCommand mySqlCommand = mySqlConnection.CreateCommand();

            mySqlCommand.CommandText = selectString;

            SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();

            mySqlDataAdapter.SelectCommand = mySqlCommand;

            DataSet myDataSet = new DataSet();

            mySqlConnection.Open();

            string dataTableName = "dictionary";
            mySqlDataAdapter.Fill(myDataSet, dataTableName);

            DataTable myDataTable = myDataSet.Tables[dataTableName];
            //now how to serialize it?

3 个答案:

答案 0 :(得分:13)

对XML来说很简单:

DataTable myTable = new DataTable();
myTable.WriteXml(@"c:\myfile");

答案 1 :(得分:1)

让我试着回答你的问题。当涉及到数据集或数据表的序列化时,不会持久存储到文件和回读。这会导致IO开销,并且在所有情况下都不可行。您需要做的是,编写一个序列化DataTable的函数。 (确保为DataTable命名以便序列化。请参阅下面C#中的示例

/ *使用此方法将给定对象序列化为XML。我们将稍后将数据表传递给* /

    private XmlElement Serialize(object obj)
    {
        XmlElement serializedXmlElement = null;  

        try
        {
            System.IO.MemoryStream memoryStream = new MemoryStream();
            System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
            xmlSerializer.Serialize(memoryStream, obj);
            memoryStream.Position = 0;

            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(memoryStream);
            serializedXmlElement = xmlDocument.DocumentElement;
        }
        catch (Exception e)
        {
            //logging statements. You must log exception for review
        }

        return serializedXmlElement; 
    }

实现Serialize方法后,您可以序列化DataTable,如下所示。为简洁起见,我不是在这里写完整个样本。

        adapter.Fill(employee);
        employee.TableName = "Employees";
        XmlElement xmlElement = (XmlElement)Serialize(employee);
        Console.WriteLine(xmlElement.ToString());
        string xmlString = xmlElement.OuterXml.ToString();

        return xmlString;

希望这会有所帮助。如果您有更多问题,请与我们联系。

答案 2 :(得分:1)

以下是如何将其转换为Json:

        DataTable dt = new DataTable();
        dt.Load(reader);
        string temp = JsonConvert.SerializeObject(dt);

如果你想将这个json转换为对象列表(可能是你的EF表),那么使用下面的代码:

dbContext db = new dbContext();
List<Object> jsonList = (List<Object>)JsonConvert.DeserializeObject(temp, typeof(List<Object>));