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
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>));
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.
To XML it's simple:
DataTable myTable = new DataTable();
myTable.WriteXml(@"c:\myfile");