如何将 DataTable 序列化为 json 或 xml

发布于 2024-08-25 13:56:23 字数 1194 浏览 3 评论 0原文

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

例如有一个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?

i'm trying to serialize DataTable to Json or XML. is it possibly and how? any tutorials and ideas, please.

For example a have a sql table:

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# code:

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

春花秋月 2024-09-01 13:56:23

对于 XML 来说很简单:

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

To XML it's simple:

DataTable myTable = new DataTable();
myTable.WriteXml(@"c:\myfile");
丶视觉 2024-09-01 13:56:23

以下是如何将其转换为 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>));

Here is how to convert it to Json:

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

and if you want to convert this json to a list of objects (it could be your EF table) then use the below:

dbContext db = new dbContext();
List<Object> jsonList = (List<Object>)JsonConvert.DeserializeObject(temp, typeof(List<Object>));
韵柒 2024-09-01 13:56:23

让我尝试回答你的问题。当涉及到数据集或数据表的序列化时,不要持久化到文件并回读。这会导致 IO 开销,并且并非在所有情况下都可行。您需要做的是编写一个函数来序列化数据表。 (确保为 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; 
    }

实现后序列化方法,您可以序列化您的数据表,如下所示,为了简洁起见,我不会在这里编写整个示例,

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

        return xmlString;

如果您有更多问题,请告诉我。

Let me try to answer your question. When it comes to serialization of a dataset or data table do not persist on to a file and readback.That causes IO overhead and is not viable in all scenarios. What you need to do is, write a function to Serialize the DataTable. (Make sure that you give a name to the DataTable inorder to serialize. See the example below in C#

/*Use this method to serialize a given object in to XML. We will pass datatable in to this later */

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

After you have implemented the Serialize method, you can serialize your DataTable as shown below. I am not writing my entire sample here for brevity.

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

        return xmlString;

Hope this helps. Please let me know if you have more questions.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文