服务器之家

服务器之家 > 正文

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

时间:2021-12-03 15:15     来源/作者:Quber

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
/// <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#程序设计有所帮助。

标签:

相关文章

热门资讯

yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
2021年耽改剧名单 2021要播出的59部耽改剧列表
2021年耽改剧名单 2021要播出的59部耽改剧列表 2021-03-05
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部