search
HomeBackend DevelopmentC#.Net TutorialImplementation code for converting DataSet, string, DataTable, and objects in C# into Json

C#中对象,字符串,dataTable、DataReader、DataSet,对象集合转换成Json字符串方法。

public class ConvertJson
 {
  #region 私有方法
  /// <summary>
  /// 过滤特殊字符
  /// </summary>
  /// <param name="s">字符串</param>
  /// <returns>json字符串</returns>
  private static string String2Json(String s)
  {
   StringBuilder sb = new StringBuilder();
   for (int i = 0; i < s.Length; i++)
   {
    char c = s.ToCharArray()[i];
    switch (c)
    {
     case &#39;\"&#39;:
      sb.Append("\\\""); break;
     case &#39;\\&#39;:
      sb.Append("\\\\"); break;
     case &#39;/&#39;:
      sb.Append("\\/"); break;
     case &#39;\b&#39;:
      sb.Append("\\b"); break;
     case &#39;\f&#39;:
      sb.Append("\\f"); break;
     case &#39;\n&#39;:
      sb.Append("\\n"); break;
     case &#39;\r&#39;:
      sb.Append("\\r"); break;
     case &#39;\t&#39;:
      sb.Append("\\t"); break;
     default:
      sb.Append(c); break;
    }
   }
   return sb.ToString();
  }
  /// <summary>
  /// 格式化字符型、日期型、布尔型
  /// </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 = str.ToLower();
   }
   else if (type != typeof(string) && string.IsNullOrEmpty(str))
   {
    str = "\"" + str + "\"";
   }
   return str;
  }
  #endregion
 
  #region list转换成JSON
  /// <summary>
  /// list转换为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, obj.GetType().Name);
  }
  /// <summary>
  /// list转换为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 (string.IsNullOrEmpty(JsonName))
    JsonName = list[0].GetType().Name;
   Json.Append("{\"" + JsonName + "\":[");
   if (list.Count > 0)
   {
    for (int i = 0; i < list.Count; i++)
    {
     T obj = Activator.CreateInstance<T>();
     PropertyInfo[] pi = obj.GetType().GetProperties();
     Json.Append("{");
     for (int j = 0; j < pi.Length; j++)
     {
      Type type = pi[j].GetValue(list[i], null).GetType();
      Json.Append("\"" + pi[j].Name.ToString() + "\":" + StringFormat(pi[j].GetValue(list[i], null).ToString(), type));
      if (j < pi.Length - 1)
      {
       Json.Append(",");
      }
     }
     Json.Append("}");
     if (i < list.Count - 1)
     {
      Json.Append(",");
     }
    }
   }
   Json.Append("]}");
   return Json.ToString();
  }
  #endregion
 
  #region 对象转换为Json
  /// <summary>
  /// 对象转换为json
  /// </summary>
  /// <param name="jsonObject">json对象</param>
  /// <returns>json字符串</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 is Guid || objectValue is TimeSpan)
    {
     value = "&#39;" + objectValue.ToString() + "&#39;";
    }
    else if (objectValue is string)
    {
     value = "&#39;" + ToJson(objectValue.ToString()) + "&#39;";
    }
    else if (objectValue is IEnumerable)
    {
     value = ToJson((IEnumerable)objectValue);
    }
    else
    {
     value = ToJson(objectValue.ToString());
    }
    jsonString += "\"" + ToJson(propertyInfo[i].Name) + "\":" + value + ",";
   }
   jsonString.Remove(jsonString.Length - 1, jsonString.Length);
   return jsonString + "}";
  }
  #endregion
 
  #region 对象集合转换为json
  /// <summary>
  /// 对象集合转换为json
  /// </summary>
  /// <param name="array">对象集合</param>
  /// <returns>json字符串</returns>
  public static string ToJson(IEnumerable array)
  {
   string jsonString = "{";
   foreach (object item in array)
   {
    jsonString += ToJson(item) + ",";
   }
   jsonString.Remove(jsonString.Length - 1, jsonString.Length);
   return jsonString + "]";
  }
  #endregion
 
  #region 普通集合转换Json
  /// <summary> 
  /// 普通集合转换Json 
  /// </summary> 
  /// <param name="array">集合对象</param> 
  /// <returns>Json字符串</returns> 
  public static string ToArrayString(IEnumerable array)
  {
   string jsonString = "[";
   foreach (object item in array)
   {
    jsonString = ToJson(item.ToString()) + ",";
   }
   jsonString.Remove(jsonString.Length - 1, jsonString.Length);
   return jsonString + "]";
  }
  #endregion
 
  #region DataSet转换为Json
  /// <summary> 
  /// DataSet转换为Json 
  /// </summary> 
  /// <param name="dataSet">DataSet对象</param> 
  /// <returns>Json字符串</returns> 
  public static string ToJson(DataSet dataSet)
  {
   string jsonString = "{";
   foreach (DataTable table in dataSet.Tables)
   {
    jsonString += "\"" + table.TableName + "\":" + ToJson(table) + ",";
   }
   jsonString = jsonString.TrimEnd(&#39;,&#39;);
   return jsonString + "}";
  }
  #endregion
 
  #region Datatable转换为Json
  /// <summary>  
  /// Datatable转换为Json  
  /// </summary> 
  /// <param name="table">Datatable对象</param>  
  /// <returns>Json字符串</returns>  
  public static string ToJson(DataTable dt)
  {
   StringBuilder jsonString = new StringBuilder();
   jsonString.Append("[");
   DataRowCollection drc = dt.Rows;
   for (int i = 0; i < drc.Count; i++)
   {
    jsonString.Append("{");
    for (int j = 0; j < dt.Columns.Count; j++)
    {
     string strKey = dt.Columns[j].ColumnName;
     string strValue = drc[i][j].ToString();
     Type type = dt.Columns[j].DataType;
     jsonString.Append("\"" + strKey + "\":");
     strValue = StringFormat(strValue, type);
     if (j < dt.Columns.Count - 1)
     {
      jsonString.Append(strValue + ",");
     }
     else
     {
      jsonString.Append(strValue);
     }
    }
    jsonString.Append("},");
   }
   jsonString.Remove(jsonString.Length - 1, 1);
   jsonString.Append("]");
   return jsonString.ToString();
  }
  /// <summary> 
  /// DataTable转换为Json  
  /// </summary> 
  public static string ToJson(DataTable dt, string jsonName)
  {
   StringBuilder Json = new StringBuilder();
   if (string.IsNullOrEmpty(jsonName))
    jsonName = dt.TableName;
   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++)
     {
      Type type = dt.Rows[i][j].GetType();
      Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + StringFormat(dt.Rows[i][j].ToString(), type));
      if (j < dt.Columns.Count - 1)
      {
       Json.Append(",");
      }
     }
     Json.Append("}");
     if (i < dt.Rows.Count - 1)
     {
      Json.Append(",");
     }
    }
   }
   Json.Append("]}");
   return Json.ToString();
  }
  #endregion
 
  #region DataReader转换为Json
  /// <summary>  
  /// DataReader转换为Json  
  /// </summary>  
  /// <param name="dataReader">DataReader对象</param>  
  /// <returns>Json字符串</returns> 
  public static string ToJson(DbDataReader dataReader)
  {
   StringBuilder jsonString = new StringBuilder();
   jsonString.Append("[");
   while (dataReader.Read())
   {
    jsonString.Append("{");
    for (int i = 0; i < dataReader.FieldCount; i++)
    {
     Type type = dataReader.GetFieldType(i);
     string strKey = dataReader.GetName(i);
     string strValue = dataReader[i].ToString();
     jsonString.Append("\"" + strKey + "\":");
     strValue = StringFormat(strValue, type);
     if (i < dataReader.FieldCount - 1)
     {
      jsonString.Append(strValue + ",");
     }
     else
     {
      jsonString.Append(strValue);
     }
    }
    jsonString.Append("},");
   }
   dataReader.Close();
   jsonString.Remove(jsonString.Length - 1, 1);
   jsonString.Append("]");
   return jsonString.ToString();
  }
  #endregion
 }

更多C#中的DataSet、string、DataTable、对象转换成Json的实现代码相关文章请关注PHP中文网!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# .NET and the Future: Adapting to New TechnologiesC# .NET and the Future: Adapting to New TechnologiesApr 14, 2025 am 12:06 AM

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

Is C# .NET Right for You? Evaluating its ApplicabilityIs C# .NET Right for You? Evaluating its ApplicabilityApr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# Code within .NET: Exploring the Programming ProcessC# Code within .NET: Exploring the Programming ProcessApr 12, 2025 am 12:02 AM

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

C# .NET: Exploring Core Concepts and Programming FundamentalsC# .NET: Exploring Core Concepts and Programming FundamentalsApr 10, 2025 am 09:32 AM

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

Testing C# .NET Applications: Unit, Integration, and End-to-End TestingTesting C# .NET Applications: Unit, Integration, and End-to-End TestingApr 09, 2025 am 12:04 AM

Testing strategies for C#.NET applications include unit testing, integration testing, and end-to-end testing. 1. Unit testing ensures that the minimum unit of the code works independently, using the MSTest, NUnit or xUnit framework. 2. Integrated tests verify the functions of multiple units combined, commonly used simulated data and external services. 3. End-to-end testing simulates the user's complete operation process, and Selenium is usually used for automated testing.

Advanced C# .NET Tutorial: Ace Your Next Senior Developer InterviewAdvanced C# .NET Tutorial: Ace Your Next Senior Developer InterviewApr 08, 2025 am 12:06 AM

Interview with C# senior developer requires mastering core knowledge such as asynchronous programming, LINQ, and internal working principles of .NET frameworks. 1. Asynchronous programming simplifies operations through async and await to improve application responsiveness. 2.LINQ operates data in SQL style and pay attention to performance. 3. The CLR of the NET framework manages memory, and garbage collection needs to be used with caution.

C# .NET Interview Questions & Answers: Level Up Your ExpertiseC# .NET Interview Questions & Answers: Level Up Your ExpertiseApr 07, 2025 am 12:01 AM

C#.NET interview questions and answers include basic knowledge, core concepts, and advanced usage. 1) Basic knowledge: C# is an object-oriented language developed by Microsoft and is mainly used in the .NET framework. 2) Core concepts: Delegation and events allow dynamic binding methods, and LINQ provides powerful query functions. 3) Advanced usage: Asynchronous programming improves responsiveness, and expression trees are used for dynamic code construction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.