ASP. NET parses DataTable into JSON

Source: Internet
Author: User

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


 

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.