Deserializes a JSON string into a DataTable supplement to JsonConvert
Source: Internet
Author: User
<span id="Label3"></p><p><p><summary><br>Extension method to deserialize a JSON string into a DataTable<br></summary><br><typeparam name= "T" > Type </typeparam><br><param name= "str" ></param><br><returns>DataTable</returns><br>public static DataTable derializetodatatable<t> (this string Str)<br>{<br>DataTable dt = new DataTable ();<br>if (str[0] = = ' [')//if The first character of STR is ' [', it means that there are multiple model data stored in STR<br>{<br>Delete the last '] ' and the first ' [', the order cannot be wrong. Otherwise the length of the string is Wrong.<br>Since each model is separated from the model with a ",", it is replaced with ";" Separated<br>str = str. Remove (str. Length-1, 1). Remove (0, 1). Replace ("},{", "}; {");<br>}<br>JavaScriptSerializer js = new JavaScriptSerializer ();<br>string[] items = str. Split (';'); /with ";" Separate multiple data lines<br>foreach (PropertyInfo property in typeof (T). GetProperties ())//reflection, Obtaining all properties of type T<br>{<br>Create a new column with the column Name property name and type as the type of the Property.<br>DataColumn col = new DataColumn (property. Name, Property. PropertyType);<br>Dt. Columns.Add (col);<br>}</p></p><p><p>loop, One-by-one Deserialization<br>for (int i = 0; i < Items. Length; I++)<br>{<br>Create a new row<br>DataRow dr = Dt. NewRow ();</p></p><p><p>Deserializes to a T-type object<br>T temp = Js. Deserialize<t> (items[i]);<br>foreach (PropertyInfo property in typeof (T). GetProperties ())<br>{<br>Assign value<br>Dr[property. Name] = Property. GetValue (temp, null);<br>}<br>Dt. Rows.Add (dr);<br>}<br>Return dt;<br>}</p></p><p><p>Deserializes a JSON string into a DataTable supplement to JsonConvert</p></p></span>
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.