Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to serialize a DataTable to json or xml

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?
like image 882
loviji Avatar asked Mar 16 '10 23:03

loviji


People also ask

Is DataTable serializable C#?

DataTable's base isn't serializable.

What is JSON data serialization?

Serialization is the process of converting . NET objects such as strings into a JSON format and deserialization is the process of converting JSON data into . NET objects.


3 Answers

To XML it's simple:

DataTable myTable = new DataTable();
myTable.WriteXml(@"c:\myfile");
like image 149
Carra Avatar answered Sep 28 '22 18:09

Carra


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>));
like image 25
M. Tamimi Avatar answered Sep 28 '22 16:09

M. Tamimi


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.

like image 36
JAYARAJ SIVADASAN Avatar answered Sep 28 '22 18:09

JAYARAJ SIVADASAN