SoFunction
Updated on 2025-03-06

Implementation code for converting DataSet, string, DataTable, and objects into Json in C#

Implementation code for converting DataSet, string, DataTable, and objects into Json in C#

Updated: September 1, 2014 01:43:02 Author: Away
This article mainly introduces the implementation code of DataSet, string, DataTable, and object conversion into Json in C#. Friends who need it can refer to it.

In C#, objects, strings, dataTable, DataReader, DataSet, and the object collection is converted into Json string methods.

public class ConvertJson
 {
  #region Private Method  /// <summary>
  /// Filter special characters  /// </summary>
  /// <param name="s">String</param>  /// <returns>json string</returns>  private static string String2Json(String s)
  {
   StringBuilder sb = new StringBuilder();
   for (int i = 0; i &lt; ; i++)
   {
    char c = ()[i];
    switch (c)
    {
     case '\"':
      ("\\\""); break;
     case '\\':
      ("\\\\"); break;
     case '/':
      ("\\/"); break;
     case '\b':
      ("\\b"); break;
     case '\f':
      ("\\f"); break;
     case '\n':
      ("\\n"); break;
     case '\r':
      ("\\r"); break;
     case '\t':
      ("\\t"); break;
     default:
      (c); break;
    }
   }
   return ();
  }
  /// &lt;summary&gt;
  /// Format character type, date type, boolean type  /// &lt;/summary&gt;
  /// &lt;param name="str"&gt;&lt;/param&gt;
  /// &lt;param name="type"&gt;&lt;/param&gt;
  /// &lt;returns&gt;&lt;/returns&gt;
  private static string StringFormat(string str, Type type)
  {
   if (type == typeof(string))
   {
    str = String2Json(str);
    str = "\"" + str + "\"";
   }
   else if (type == typeof(DateTime))
   {
    str = "\"" + str + "\"";
   }
   else if (type == typeof(bool))
   {
    str = ();
   }
   else if (type != typeof(string) &amp;&amp; (str))
   {
    str = "\"" + str + "\"";
   }
   return str;
  }
  #endregion

  #region list to JSON  /// &lt;summary&gt;
  /// Convert list to Json  /// &lt;/summary&gt;
  /// &lt;typeparam name="T"&gt;&lt;/typeparam&gt;
  /// &lt;param name="list"&gt;&lt;/param&gt;
  /// &lt;returns&gt;&lt;/returns&gt;
  public static string ListToJson&lt;T&gt;(IList&lt;T&gt; list)
  {
   object obj = list[0];
   return ListToJson&lt;T&gt;(list, ().Name);
  }
  /// &lt;summary&gt;
  /// Convert list to json  /// &lt;/summary&gt;
  /// &lt;typeparam name="T1"&gt;&lt;/typeparam&gt;
  /// &lt;param name="list"&gt;&lt;/param&gt;
  /// &lt;param name="p"&gt;&lt;/param&gt;
  /// &lt;returns&gt;&lt;/returns&gt;
  private static string ListToJson&lt;T&gt;(IList&lt;T&gt; list, string JsonName)
  {
   StringBuilder Json = new StringBuilder();
   if ((JsonName))
    JsonName = list[0].GetType().Name;
   ("{\"" + JsonName + "\":[");
   if ( &gt; 0)
   {
    for (int i = 0; i &lt; ; i++)
    {
     T obj = &lt;T&gt;();
     PropertyInfo[] pi = ().GetProperties();
     ("{");
     for (int j = 0; j &lt; ; j++)
     {
      Type type = pi[j].GetValue(list[i], null).GetType();
      ("\"" + pi[j].() + "\":" + StringFormat(pi[j].GetValue(list[i], null).ToString(), type));
      if (j &lt;  - 1)
      {
       (",");
      }
     }
     ("}");
     if (i &lt;  - 1)
     {
      (",");
     }
    }
   }
   ("]}");
   return ();
  }
  #endregion

  #region object converted to Json  /// &lt;summary&gt;
  /// Convert object to json  /// &lt;/summary&gt;
  /// <param name="jsonObject">json object</param>  /// <returns>json string</returns>  public static string ToJson(object jsonObject)
  {
   string jsonString = "{";
   PropertyInfo[] propertyInfo = ().GetProperties();
   for (int i = 0; i &lt; ; i++)
   {
    object objectValue = propertyInfo[i].GetGetMethod().Invoke(jsonObject, null);
    string value = ;
    if (objectValue is DateTime || objectValue is Guid || objectValue is TimeSpan)
    {
     value = "'" + () + "'";
    }
    else if (objectValue is string)
    {
     value = "'" + ToJson(()) + "'";
    }
    else if (objectValue is IEnumerable)
    {
     value = ToJson((IEnumerable)objectValue);
    }
    else
    {
     value = ToJson(());
    }
    jsonString += "\"" + ToJson(propertyInfo[i].Name) + "\":" + value + ",";
   }
   ( - 1, );
   return jsonString + "}";
  }
  #endregion

  #region object collection converted to json  /// &lt;summary&gt;
  /// Convert object collection to json  /// &lt;/summary&gt;
  /// <param name="array">Object collection</param>  /// <returns>json string</returns>  public static string ToJson(IEnumerable array)
  {
   string jsonString = "{";
   foreach (object item in array)
   {
    jsonString += ToJson(item) + ",";
   }
   ( - 1, );
   return jsonString + "]";
  }
  #endregion

  #region Normal collection conversion Json  /// &lt;summary&gt; 
  /// Normal collection conversion Json  /// &lt;/summary&gt; 
  /// <param name="array">collection object</param>  /// <returns>Json string</returns>  public static string ToArrayString(IEnumerable array)
  {
   string jsonString = "[";
   foreach (object item in array)
   {
    jsonString = ToJson(()) + ",";
   }
   ( - 1, );
   return jsonString + "]";
  }
  #endregion

  #region DataSet convert to Json  /// &lt;summary&gt; 
  /// Convert DataSet to Json  /// &lt;/summary&gt; 
  /// <param name="dataSet">DataSet object</param>  /// <returns>Json string</returns>  public static string ToJson(DataSet dataSet)
  {
   string jsonString = "{";
   foreach (DataTable table in )
   {
    jsonString += "\"" +  + "\":" + ToJson(table) + ",";
   }
   jsonString = (',');
   return jsonString + "}";
  }
  #endregion

  #region Datatable to Json  /// &lt;summary&gt;  
  /// Convert Datatable to Json  /// &lt;/summary&gt; 
  /// <param name="table">Datatable object</param>  /// <returns>Json string</returns>  public static string ToJson(DataTable dt)
  {
   StringBuilder jsonString = new StringBuilder();
   ("[");
   DataRowCollection drc = ;
   for (int i = 0; i &lt; ; i++)
   {
    ("{");
    for (int j = 0; j &lt; ; j++)
    {
     string strKey = [j].ColumnName;
     string strValue = drc[i][j].ToString();
     Type type = [j].DataType;
     ("\"" + strKey + "\":");
     strValue = StringFormat(strValue, type);
     if (j &lt;  - 1)
     {
      (strValue + ",");
     }
     else
     {
      (strValue);
     }
    }
    ("},");
   }
   ( - 1, 1);
   ("]");
   return ();
  }
  /// &lt;summary&gt; 
  /// Convert DataTable to Json  /// &lt;/summary&gt; 
  public static string ToJson(DataTable dt, string jsonName)
  {
   StringBuilder Json = new StringBuilder();
   if ((jsonName))
    jsonName = ;
   ("{\"" + jsonName + "\":[");
   if ( &gt; 0)
   {
    for (int i = 0; i &lt; ; i++)
    {
     ("{");
     for (int j = 0; j &lt; ; j++)
     {
      Type type = [i][j].GetType();
      ("\"" + [j].() + "\":" + StringFormat([i][j].ToString(), type));
      if (j &lt;  - 1)
      {
       (",");
      }
     }
     ("}");
     if (i &lt;  - 1)
     {
      (",");
     }
    }
   }
   ("]}");
   return ();
  }
  #endregion

  #region DataReader to Json  /// &lt;summary&gt;  
  /// Convert DataReader to Json  /// &lt;/summary&gt;  
  /// <param name="dataReader">DataReader object</param>  /// <returns>Json string</returns>  public static string ToJson(DbDataReader dataReader)
  {
   StringBuilder jsonString = new StringBuilder();
   ("[");
   while (())
   {
    ("{");
    for (int i = 0; i &lt; ; i++)
    {
     Type type = (i);
     string strKey = (i);
     string strValue = dataReader[i].ToString();
     ("\"" + strKey + "\":");
     strValue = StringFormat(strValue, type);
     if (i &lt;  - 1)
     {
      (strValue + ",");
     }
     else
     {
      (strValue);
     }
    }
    ("},");
   }
   ();
   ( - 1, 1);
   ("]");
   return ();
  }
  #endregion
 }
  • DataSet
  • string
  • DataTable
  • Json

Related Articles

  • Detailed explanation of the concept and use of delegation in C#

    The delegate name is magical, but it is essentially functional programming, passing the function as a parameter to another parameter. This article mainly introduces the concept and use of commissions in C#. If you need it, please refer to it.
    2023-02-02
  • Introduction to the difference between asynchronous and multithreading in C#

    This article introduces the difference between asynchronous and multi-threading in C#, which has certain reference learning value for everyone's learning or work. Friends who need it, please learn with the editor below.
    2022-05-05
  • C# Standard Event Stream Instance Code

    This article mainly introduces the example code of C# standard event stream. The explanation in the article is very detailed. The code helps everyone better understand and learn. Interested friends can understand it.
    2020-07-07
  • Production of test answering system based on C#

    This article mainly introduces in detail how to use C# to create an exam answering system with forms. The sample code in the article is introduced in detail and has certain reference value. Interested friends can refer to it.
    2022-03-03
  • How to export text content to word documents in C#

    This article mainly introduces the method of exporting text content to word documents in C#, and involves relevant skills for C# manipulating word documents. Friends who need it can refer to it.
    2015-04-04
  • c# wpf uses class library to realize map track playback

    This article mainly introduces the use of c# wpf class library to realize map trajectory playback methods, helping everyone better understand and learn how to use c#. Interested friends can learn about it.
    2021-03-03
  • C#/Java connection and usage skills

    I accidentally discovered that C#/Java connection sqlite and usage techniques. After checking it out, it was pretty good. Let me share it with you.
    2013-04-04
  • C# console realizes flying chess game

    This article mainly introduces the C# console to implement flying chess game. The sample code in the article is introduced in detail and has a certain reference value. Interested friends can refer to it.
    2021-07-07
  • C# Memento Pattern Example Tutorial

    This article mainly introduces the C# memorandum pattern (Memento Pattern), and uses an example that supports fallback operation to describe the implementation method of the C# memorandum pattern. Friends who need it can refer to it.
    2014-09-09
  • Summary of FAQs in C#

    This article mainly introduces a summary of common problems in C# and summarizes common techniques in C#. It is very practical. Friends who need it can refer to it.
    2014-09-09

Latest Comments