I haven't written an article for a long time. I miss this garden. Today we will introduce you to the process of parsing Datatable into json, which is not too complicated. We will introduce this article to the people who need it.
Here, the Newtonsoft. json. dll assembly is used for Json parsing. See the code below:
View Code
1 using System;
2 using System. Collections. Generic;
3 using System. Linq;
4 using System. Web;
5 using System. Data;
6 using Newtonsoft. Json;
7
8 /// <summary>
9 // DataTable parse JSON
10 /// </summary>
11 public class ConvertDataTable: JsonConverter
12 {
13 public ConvertDataTable ()
14 {
15 //
16 // TODO: add the constructor logic here
17 //
18}
19 public override bool CanConvert (Type objectType)
20 {
21 return typeof (DataTable). IsAssignableFrom (objectType );
22}
23
24 public override object ReadJson (JsonReader reader, Type objectType)
25 {
26 throw new NotImplementedException ();
27}
28
29 public override void WriteJson (JsonWriter writer, object value)
30 {
31 DataTable dt = (DataTable) value;
32 writer. WriteStartArray ();
33 foreach (DataRow dr in dt. Rows)
34 {
35 writer. WriteStartObject ();
36 foreach (DataColumn dc in dt. Columns)
37 {
38 writer. WritePropertyName (dc. ColumnName );
39 writer. WriteValue (dr [dc]. ToString ());
40}
41 writer. WriteEndObject ();
42}
43 writer. WriteEndArray ();
44}
45}
Use the above class and then call the following method to convert the datatable to json.
JavaScriptConvert. SerializeObject (dt, new ConvertDataTable ())
If you need this assembly, you can leave a message or go down one from the Internet. Thank you!
Written by Tian nishou