We usually use JavaScriptSerializer or JSON. NET to serialize an object, but for a Datatable, the data contained is more important than its serializable attributes.
I tried to convert DataRow into a Directory object, put every Directory object in the List, and finally generated an array of DataRow. The Code is as follows:
/// <Summary> /// convert the DataTable to json /// </summary> /// <param name = "dt"> DataTable </param> /// <returns> json data </returns> public static string ToJson (DataTable dt) {List <Dictionary <string, object> list = new List <Dictionary <string, object> (); foreach (DataRow dr in dt. rows) {Dictionary <string, object> result = new Dictionary <string, object> (); foreach (DataColumn dc in dt. columns) {result. add (dc. columnName, dr [dc]);} list. add (result);} return SerializeToJson (list );}
/// <Summary> /// the serialized object is a Json string /// </summary> /// <param name = "obj"> object to be serialized </param> /// <param name = "recursionLimit"> serialization object depth, the default value is 100 </param> /// <returns> Json string </returns> public static string SerializeToJson (this object obj, int recursionLimit = 100) {JavaScriptSerializer serialize = new JavaScriptSerializer (); serialize. recursionLimit = recursionLimit; return serialize. serialize (obj );}