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 < ; 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 (); } /// <summary> /// Format character type, date type, boolean type /// </summary> /// <param name="str"></param> /// <param name="type"></param> /// <returns></returns> 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) && (str)) { str = "\"" + str + "\""; } return str; } #endregion #region list to JSON /// <summary> /// Convert list to Json /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list"></param> /// <returns></returns> public static string ListToJson<T>(IList<T> list) { object obj = list[0]; return ListToJson<T>(list, ().Name); } /// <summary> /// Convert list to json /// </summary> /// <typeparam name="T1"></typeparam> /// <param name="list"></param> /// <param name="p"></param> /// <returns></returns> private static string ListToJson<T>(IList<T> list, string JsonName) { StringBuilder Json = new StringBuilder(); if ((JsonName)) JsonName = list[0].GetType().Name; ("{\"" + JsonName + "\":["); if ( > 0) { for (int i = 0; i < ; i++) { T obj = <T>(); PropertyInfo[] pi = ().GetProperties(); ("{"); for (int j = 0; j < ; j++) { Type type = pi[j].GetValue(list[i], null).GetType(); ("\"" + pi[j].() + "\":" + StringFormat(pi[j].GetValue(list[i], null).ToString(), type)); if (j < - 1) { (","); } } ("}"); if (i < - 1) { (","); } } } ("]}"); return (); } #endregion #region object converted to Json /// <summary> /// Convert object to json /// </summary> /// <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 < ; 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 /// <summary> /// Convert object collection to json /// </summary> /// <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 /// <summary> /// Normal collection conversion Json /// </summary> /// <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 /// <summary> /// Convert DataSet 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 ) { jsonString += "\"" + + "\":" + ToJson(table) + ","; } jsonString = (','); return jsonString + "}"; } #endregion #region Datatable to Json /// <summary> /// Convert Datatable to Json /// </summary> /// <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 < ; i++) { ("{"); for (int j = 0; j < ; j++) { string strKey = [j].ColumnName; string strValue = drc[i][j].ToString(); Type type = [j].DataType; ("\"" + strKey + "\":"); strValue = StringFormat(strValue, type); if (j < - 1) { (strValue + ","); } else { (strValue); } } ("},"); } ( - 1, 1); ("]"); return (); } /// <summary> /// Convert DataTable to Json /// </summary> public static string ToJson(DataTable dt, string jsonName) { StringBuilder Json = new StringBuilder(); if ((jsonName)) jsonName = ; ("{\"" + jsonName + "\":["); if ( > 0) { for (int i = 0; i < ; i++) { ("{"); for (int j = 0; j < ; j++) { Type type = [i][j].GetType(); ("\"" + [j].() + "\":" + StringFormat([i][j].ToString(), type)); if (j < - 1) { (","); } } ("}"); if (i < - 1) { (","); } } } ("]}"); return (); } #endregion #region DataReader to Json /// <summary> /// Convert DataReader to Json /// </summary> /// <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 < ; i++) { Type type = (i); string strKey = (i); string strValue = dataReader[i].ToString(); ("\"" + strKey + "\":"); strValue = StringFormat(strValue, type); if (i < - 1) { (strValue + ","); } else { (strValue); } } ("},"); } (); ( - 1, 1); ("]"); return (); } #endregion }
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-02Introduction 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-05C# 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-07Production 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-03How 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-04c# 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-03C#/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-04C# 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-07C# 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-09Summary 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