Able serialized as a JSON string

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.