C#实现集合转换成json格式数据的方法

时间:2022-06-29 00:29:49

本文实例讲述了C#实现集合转换成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
/// <summary>
/// dataTable转换成Json格式
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static string ToJson(DataTable dt)
{
  if (dt != null && dt.Rows.Count > 0)
  {
    StringBuilder jsonBuilder = new StringBuilder();
    jsonBuilder.Append("{\"");
    jsonBuilder.Append("data");
    jsonBuilder.Append("\":[");
    for (int i = 0; i < dt.Rows.Count; i++)
    {
      jsonBuilder.Append("{");
      for (int j = 0; j < dt.Columns.Count; j++)
      {
        jsonBuilder.Append("\"");
        jsonBuilder.Append(dt.Columns[j].ColumnName);
        jsonBuilder.Append("\":\"");
        jsonBuilder.Append(jsonStringFromat(dt.Rows[i][j].ToString()));
        jsonBuilder.Append("\",");
      }
      jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
      jsonBuilder.Append("},");
    }
    jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
    jsonBuilder.Append("]");
    jsonBuilder.Append("}");
    return jsonBuilder.ToString();
  }
  else
  {
    return "";
  }
}
/// <summary>
/// Enumerable转成JSON
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
public static string EnumerableToJson(IEnumerable list)
{
  StringBuilder json = new StringBuilder();
  int i = 0;
  if (list != null)
  {
    json.Append("{\"data\":[");
    foreach (var item in list)
    {
      json.Append("{");
      PropertyInfo[] pi = item.GetType().GetProperties();
      int j = 0;
      foreach (var p in pi)
      {
        if (j < pi.Length - 1)
        {
          json.Append("\"" + p.Name.ToString() + "\":\"" + jsonStringFromat(p.GetValue(item, null).ToString()) + "\",");
        }
        else
        {
          json.Append("\"" + p.Name.ToString() + "\":\"" + jsonStringFromat(p.GetValue(item, null).ToString()) + "\"");
        }
        j++;
      }
      i++;
      json.Append("},");
    }
    json.Remove(json.Length - 1, 1);
    json.Append("]}");
  }
  if (i != 0)
    return json.ToString();
  else
    return "";
}

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