C#实现DataTable,List和Json转换的方法

前端技术 2023/09/09 C#

本文实例讲述了C#实现DataTable,List和Json转换的方法。分享给大家供大家参考,具体如下:

1. 将DataTable或Ilist<>转换成JSON格式

using System;
using System.Data;
using System.Text;
using System.Collections.Generic;
using System.Reflection;
/// <summary>
/// 将DataTable或Ilist<>转换成JSON格式
/// </summary>
public class ToJson
{
  public ToJson()
  {
  }
//DataTable转成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转成json
  public static string ObjectToJson<T>(string jsonName, IList<T> IL)
  {
    StringBuilder Json = 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. 各种数据集转换为json

/// <summary>
/// 对象转换为Json字符串
/// </summary>
/// <param name=\"jsonObject\">对象</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 = \"\'\" + objectValue.ToString() + \"\'\";
    }
    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>
/// 对象集合转换Json
/// </summary>
/// <param name=\"array\">集合对象</param>
/// <returns>Json字符串</returns>
public static string ToJson(IEnumerable array)
{
  string jsonString = \"[\";
  foreach (object item in array)
  {
    jsonString += Json.ToJson(item) + \",\";
  }
  return Json.DeleteLast(jsonString) + \"]\";
}
/// <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()) + \",\";
  }
  return Json.DeleteLast(jsonString) + \"]\";
}
/// <summary>
/// 删除结尾字符
/// </summary>
/// <param name=\"str\">需要删除的字符</param>
/// <returns>完成后的字符串</returns>
private static string DeleteLast(string str)
{
  if (str.Length > 1)
  {
    return str.Substring(0, str.Length - 1);
  }
  return str;
}
/// <summary>
/// Datatable转换为Json
/// </summary>
/// <param name=\"table\">Datatable对象</param>
/// <returns>Json字符串</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转换为Json
/// </summary>
/// <param name=\"dataReader\">DataReader对象</param>
/// <returns>Json字符串</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转换为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 += \"\\\"\" + ToJson(table.TableName) + \"\\\":\" + ToJson(table) + \",\";
  }
  return jsonString = DeleteLast(jsonString) + \"}\";
}
/// <summary>
/// String转换为Json
/// </summary>
/// <param name=\"value\">String对象</param>
/// <returns>Json字符串</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;
}

更多关于C#相关内容感兴趣的读者可查看本站专题:《C#窗体操作技巧汇总》、《C#常见控件用法教程》、《WinForm控件用法总结》、《C#程序设计之线程使用技巧总结》、《C#操作Excel技巧总结》、《C#中XML文件操作技巧汇总》、《C#数据结构与算法教程》、《C#数组操作技巧总结》及《C#面向对象程序设计入门教程》

希望本文所述对大家C#程序设计有所帮助。

本文地址:https://www.stayed.cn/item/23884

转载请注明出处。

本站部分内容来源于网络,如侵犯到您的权益,请 联系我

我的博客

人生若只如初见,何事秋风悲画扇。