C # ways to implement Datatable,list and JSON transformations _c# tutorials

Source: Internet
Author: User
Tags datetime tojson

This article illustrates how C # implements Datatable,list and JSON transformations. Share to everyone for your reference, specific as follows:

1. Convert a DataTable or ilist<> into JSON format

Using System;
Using System.Data;
Using System.Text;
Using System.Collections.Generic;
Using System.Reflection; 
  <summary> convert DataTable or ilist<> to JSON format///</summary> public class Tojson {///Tojson () { //datatable to JSON public static string Datatabletojson (String jsonname, DataTable dt) {StringBuilder JSON =
    New StringBuilder ();
    Json.append ("{\" "+ Jsonname +" \ ": ["); if (dt. Rows.Count > 0) {for (int i = 0; i < dt. Rows.Count;
        i++) {json.append ("{"); for (int j = 0; j < dt.) Columns.count; J + +) {json.append ("\" + dt. COLUMNS[J]. Columnname.tostring () + "\": \ "" + dt. ROWS[I][J].
          ToString () + "\" "); if (J < dt.
          columns.count-1) {json.append (",");
        } json.append ("}"); if (i < dt.
        rows.count-1) {json.append (",");
    }} json.append ("]}");
 return json.tostring (); //list to JSON public static string objecttojson<t> (String jsonname, ilist<t> IL) {StringBuilder JSO
    n = new StringBuilder ();
    Json.append ("{\" "+ Jsonname +" \ ": ["); if (IL. Count > 0) {for (int i = 0; i < IL. Count;
        i++) {T obj = activator.createinstance<t> (); Type type = obj.
        GetType (); propertyinfo[] PiS = type.
        GetProperties ();
        Json.append ("{"); for (int j = 0; J < PiS. Length; J + +) {json.append ("\" + pis[j]. Name.tostring () + "\": \ "" + pis[j].
          GetValue (Il[i], null) + "\"); if (J < PiS.
          Length-1) {json.append (",");
        } json.append ("}"); if (I < IL.
        Count-1) {json.append (",");
    }} json.append ("]}");
  return json.tostring ();

 }
}

2. Convert various datasets to JSON

<summary>///object to JSON string///</summary>///<param name= "Jsonobject" > Object </param>///<re
  Turns>json string </returns> public static string Tojson (object jsonobject) {string jsonstring = "{"; propertyinfo[] PropertyInfo = Jsonobject.gettype ().
  GetProperties (); for (int i = 0; i < propertyinfo.length i++) {Object objectvalue = Propertyinfo[i]. Getgetmethod ().
    Invoke (jsonobject, NULL); String value = String.
    Empty; if (Objectvalue is DateTime | | Objectvalue was GUID | | Objectvalue is TimeSpan) {value = "'" + objectvalue.tostr
    ING () + "'";
    else if (Objectvalue is string) {value = ' ' + Tojson (objectvalue.tostring ()) + "'";
    else if (Objectvalue is IEnumerable) {value = Tojson ((IEnumerable) objectvalue);
    else {value = Tojson (objectvalue.tostring ()); } jsonstring + = "\" + Tojson (propertyinfo[i).
  Name) + "\": "+ Value +", "; Return Json.deletelast (jsonstRing) + "}"; ///<summary>///Object collection convert JSON///</summary>///<param name= "Array" > Collection Object </param>///<return
  S>json string </returns> public static string Tojson (IEnumerable array) {string jsonstring = "[";
  foreach (object item in array) {jsonstring + + Json.tojson (item) + ",";
Return Json.deletelast (jsonstring) + "]"; ///<summary>///Normal collection convert JSON///</summary>///<param name= "Array" > Collection Object </param>///<return
  S>json string </returns> public static string toarraystring (IEnumerable array) {string jsonstring = "["; foreach (object item in array) {jsonstring = Tojson (item.
  ToString ()) + ",";
Return Json.deletelast (jsonstring) + "]"; ///<summary>///Delete End character///</summary>///<param name= "str" > Character </param>///to be removed &LT;RETURNS&G t; completed string </returns> private static string Deletelast (String str) {if (str). Length > 1) {return str. Substring (0, str. LENGTH-1);
  return str;
///<summary>///DataTable converted to JSON///</summary>///<param name= "table" >datatable object </param>
  <returns>json string </returns> public static string Tojson (DataTable table) {string jsonstring = ' ['; DataRowCollection DRC = table.
  Rows; for (int i = 0; i < DRC. Count;
    i++) {jsonstring + = "{"; foreach (DataColumn column in table. Columns) {jsonstring + = "\" + Tojson (column.
      ColumnName) + "\": "; if (column. DataType = = typeof (DateTime) | | Column. DataType = = typeof (String)) {jsonstring + = "\" + Tojson (drc[i][column. ColumnName].
      ToString ()) + "\", "; else {jsonstring + = Tojson (drc[i][column. ColumnName].
      ToString ()) + ",";
  } jsonstring = Deletelast (jsonstring) + "},";
Return Deletelast (jsonstring) + "]"; ///<summary>///DataReader convert to JSON///</summary>///<param name= "DataReader" >datareader object </ Param>///<returNs>json string </returns> public static string Tojson (DbDataReader dataReader) {string jsonstring = "[;
    while (Datareader.read ()) {jsonstring = = "{"; 
      for (int i = 0; i < Datareader.fieldcount i++) {jsonstring + = "\" + Tojson (Datareader.getname (i)) + "\": ";
        if (Datareader.getfieldtype (i) = = typeof (DateTime) | | datareader.getfieldtype (i) = = typeof (String)) { Jsonstring + = "" "+ Tojson (datareader[i).
      ToString ()) + "\", "; else {jsonstring + = Tojson (datareader[i).
      ToString ()) + ",";
  } jsonstring = Deletelast (jsonstring) + "}";
  } datareader.close ();
Return Deletelast (jsonstring) + "]"; ///<summary>///DataSet converted to JSON///</summary>///<param name= "DataSet" >dataset object </param>//
  /<returns>json string </returns> public static string Tojson (DataSet DataSet) {string jsonstring = ' {'; foreach (DataTable table in dataset.tables) {jsonstring + = "\""+ tojson (table.)
  TableName) + "\": "+ tojson (table) +";
return jsonstring = Deletelast (jsonstring) + "}"; ///<summary>///string Convert to JSON///</summary>///<param name= "value" >string object </param>/// ; Returns>json string </returns> public static string Tojson (string value) {if (string). IsNullOrEmpty (value)) {return string.
  Empty;
  } string Temstr;
  Temstr = value; Temstr = Temstr. Replace ("{", "{"). Replace ("}", "}"). Replace (":", ":"). Replace (",", ","). Replace ("[", "" "). Replace ("]", "" ""). Replace (";", ";"). Replace ("\ n", "<br/>").
  Replace ("\ R", ""); Temstr = Temstr.
  Replace ("T", ""); Temstr = Temstr.
  Replace ("'", "\"); Temstr = Temstr.
  Replace (@ "\", @ "\"); Temstr = Temstr.
  Replace ("\" "," \ "\");
return temstr;

 }

Read more about C # Interested readers can view the site topics: "C # form Operation Tips Summary", "C # Common control usage Tutorial", "WinForm Control Usage Summary", "C # Programming Thread Usage Skills summary", "C # Operation Excel Skills Summary", "C # Summary of operational skills in XML files, C # tutorial on data structure and algorithms, C # array operation techniques Summary, and C # Introduction to object-oriented Programming

I hope this article will help you with C # programming.

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.