123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- using Newtonsoft.Json;
- using Newtonsoft.Json.Linq;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace AnHuiMI.Common
- {
- class StringUtils
- {
- public static long CurrentTimeStamp(bool isMinseconds = false)
- {
- TimeSpan timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
- return Convert.ToInt64(isMinseconds ? timeSpan.TotalMilliseconds : timeSpan.TotalSeconds);
- }
- public static SortedDictionary<string, object> KeySort(JObject obj)
- {
- var dic = new SortedDictionary<string, object>();
- foreach (var x in obj)
- {
- if (x.Value is JValue) dic.Add(x.Key, x.Value);
- else if (x.Value is JObject) dic.Add(x.Key, KeySort((JObject)x.Value));
- else if (x.Value is JArray)
- {
- var tmp = new SortedDictionary<string, object>[x.Value.Count()];
- for (var i = 0; i < x.Value.Count(); i++)
- {
- tmp[i] = KeySort((JObject)x.Value[i]);
- }
- dic.Add(x.Key, tmp);
- }
- }
- return dic;
- }
- /// <summary>
- /// 删除为空值的属性
- /// </summary>
- /// <param name="joInput"></param>
- /// <returns></returns>
- public static JObject removeEmptyProperty(JObject joInput)
- {
- JObject joOutput = new JObject();
- foreach (var x in joInput)
- {
- if (x.Value is JValue)
- {
- if (!string.IsNullOrEmpty(x.Value.ToString()))
- {
- joOutput.Add(x.Key, x.Value);
- }
- }
- else if (x.Value is JObject) joOutput.Add(x.Key, removeEmptyProperty((JObject)x.Value));
- else if (x.Value is JArray)
- {
- JArray tmp = new JArray();
- for (var i = 0; i < x.Value.Count(); i++)
- {
- tmp.Add(removeEmptyProperty((JObject)x.Value[i]));
- }
- joOutput.Add(x.Key, tmp);
- }
- }
- return joOutput;
- }
- public static string SortJson(string json)
- {
- SortedDictionary<string, object> keyValues = KeySort(JObject.Parse(json));
- keyValues.OrderBy(m => m.Key);
- return JsonConvert.SerializeObject(keyValues);
- }
- public static string Json2sign(string json)
- {
- Dictionary<string, object> dictionary = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
- string text = "";
- foreach (KeyValuePair<string, object> keyValuePair in dictionary)
- {
- // 值为空不参与签名
- //if (!string.IsNullOrEmpty(keyValuePair.Value + ""))
- //{
- text = string.Concat(new object[]
- {
- text,
- keyValuePair.Key,
- "=",
- keyValuePair.Value,
- "&"
- });
- //}
- }
- return text.Substring(0, text.Length - 1);
- }
- }
- }
|