Utility.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Text.Json;
  7. using System.Threading.Tasks;
  8. namespace ddq
  9. {
  10. public class Utility
  11. {
  12. public static readonly Dictionary<int, string> RoleType = new Dictionary<int, string>
  13. {
  14. { 1, "Portfolio Manager" },
  15. { 2, "Researcher"},
  16. { 3, "Contactor"},
  17. { 4, "Marketing"},
  18. { 5, "Risk & Compliance"},
  19. { 6, "Executive"},
  20. { 7, "Legal"},
  21. { 8, "Trading"},
  22. { 9, "Technology"},
  23. { 0, "Other"}
  24. };
  25. /// <summary>
  26. /// JsonElment 转为字符串,若输入为空则输出""
  27. /// </summary>
  28. /// <param name="jsonElement"></param>
  29. /// <returns></returns>
  30. public static string Json2Text(JsonElement jsonElement, string propertyName)
  31. {
  32. string str = "";
  33. JsonElement elm;
  34. if (propertyName == null) return str;
  35. bool hasProperty = jsonElement.TryGetProperty(propertyName, out elm);
  36. if (hasProperty == true && elm.ValueKind != JsonValueKind.Undefined)
  37. {
  38. str = elm.ToString().Trim();
  39. }
  40. return str;
  41. }
  42. public static DataTable Json2Table(JsonElement jsonElement)
  43. {
  44. DataTable dataTable = new DataTable();
  45. // 如果解析出的是数组
  46. if (jsonElement.ValueKind == JsonValueKind.Array)
  47. {
  48. // 遍历数组元素
  49. foreach (JsonElement element in jsonElement.EnumerateArray())
  50. {
  51. // 如果是第一次遍历,元素包含列定义信息,需要创建列
  52. if (dataTable.Columns.Count == 0)
  53. {
  54. // 遍历第一个对象的属性来创建列
  55. foreach (JsonProperty property in element.EnumerateObject())
  56. {
  57. dataTable.Columns.Add(property.Name);
  58. }
  59. }
  60. // 创建新行并填充数据
  61. DataRow newRow = dataTable.NewRow();
  62. foreach (JsonProperty property in element.EnumerateObject())
  63. {
  64. newRow[property.Name] = property.Value.ToString();
  65. }
  66. dataTable.Rows.Add(newRow);
  67. }
  68. }
  69. return dataTable;
  70. }
  71. public static List<Dictionary<string, object>> DataTable2List(DataTable dataTable)
  72. {
  73. var records = new List<Dictionary<string, object>>();
  74. foreach (DataRow row in dataTable.Rows)
  75. {
  76. var record = new Dictionary<string, object>();
  77. foreach (DataColumn col in dataTable.Columns)
  78. {
  79. // 处理DBNull值
  80. record[col.ColumnName] = row[col] == DBNull.Value ? null : row[col];
  81. }
  82. records.Add(record);
  83. }
  84. return records;
  85. }
  86. }
  87. }