StringUtils.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. using Newtonsoft.Json;
  2. using Newtonsoft.Json.Linq;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace AnHuiMI.Common
  9. {
  10. class StringUtils
  11. {
  12. public static long CurrentTimeStamp(bool isMinseconds = false)
  13. {
  14. TimeSpan timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
  15. return Convert.ToInt64(isMinseconds ? timeSpan.TotalMilliseconds : timeSpan.TotalSeconds);
  16. }
  17. public static SortedDictionary<string, object> KeySort(JObject obj)
  18. {
  19. var dic = new SortedDictionary<string, object>();
  20. foreach (var x in obj)
  21. {
  22. if (x.Value is JValue) dic.Add(x.Key, x.Value);
  23. else if (x.Value is JObject) dic.Add(x.Key, KeySort((JObject)x.Value));
  24. else if (x.Value is JArray)
  25. {
  26. var tmp = new SortedDictionary<string, object>[x.Value.Count()];
  27. for (var i = 0; i < x.Value.Count(); i++)
  28. {
  29. tmp[i] = KeySort((JObject)x.Value[i]);
  30. }
  31. dic.Add(x.Key, tmp);
  32. }
  33. }
  34. return dic;
  35. }
  36. /// <summary>
  37. /// 删除为空值的属性
  38. /// </summary>
  39. /// <param name="joInput"></param>
  40. /// <returns></returns>
  41. public static JObject removeEmptyProperty(JObject joInput)
  42. {
  43. JObject joOutput = new JObject();
  44. foreach (var x in joInput)
  45. {
  46. if (x.Value is JValue)
  47. {
  48. if (!string.IsNullOrEmpty(x.Value.ToString()))
  49. {
  50. joOutput.Add(x.Key, x.Value);
  51. }
  52. }
  53. else if (x.Value is JObject) joOutput.Add(x.Key, removeEmptyProperty((JObject)x.Value));
  54. else if (x.Value is JArray)
  55. {
  56. JArray tmp = new JArray();
  57. for (var i = 0; i < x.Value.Count(); i++)
  58. {
  59. tmp.Add(removeEmptyProperty((JObject)x.Value[i]));
  60. }
  61. joOutput.Add(x.Key, tmp);
  62. }
  63. }
  64. return joOutput;
  65. }
  66. public static string SortJson(string json)
  67. {
  68. SortedDictionary<string, object> keyValues = KeySort(JObject.Parse(json));
  69. keyValues.OrderBy(m => m.Key);
  70. return JsonConvert.SerializeObject(keyValues);
  71. }
  72. public static string Json2sign(string json)
  73. {
  74. Dictionary<string, object> dictionary = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
  75. string text = "";
  76. foreach (KeyValuePair<string, object> keyValuePair in dictionary)
  77. {
  78. // 值为空不参与签名
  79. //if (!string.IsNullOrEmpty(keyValuePair.Value + ""))
  80. //{
  81. text = string.Concat(new object[]
  82. {
  83. text,
  84. keyValuePair.Key,
  85. "=",
  86. keyValuePair.Value,
  87. "&"
  88. });
  89. //}
  90. }
  91. return text.Substring(0, text.Length - 1);
  92. }
  93. }
  94. }