how to serialize a DataTable to json or xml

一笑奈何 提交于 2020-01-03 08:45:13

问题


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?

回答1:


To XML it's simple:

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



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/2458847/how-to-serialize-a-datatable-to-json-or-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!