/// <summary> /// 获取排序后的json字符串 /// </summary> /// <param name="obj"></param> /// <returns></returns> public static string GetSortStrJson(object obj) { JsonSerializerSettings setting = new JsonSerializerSettings(); setting.NullValueHandling = NullValueHandling.Ignore;//null值不序列化 string strPostData = JsonConvert.SerializeObject(obj, Formatting.None, setting); JObject jObject = JObject.Parse(strPostData); SortedDictionary<string, object> target = KeySort(jObject); strPostData = JsonConvert.SerializeObject(target); return strPostData; } /// <summary> /// 按ascii顺序排序json对象的顺序 /// </summary> /// <param name="obj"></param> /// <returns></returns> private static SortedDictionary<string, object> KeySort(JObject obj) { var res = new SortedDictionary<string, object>(); foreach (var x in obj) { if (x.Value is JValue) res.Add(x.Key, x.Value); else if (x.Value is JObject) res.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]); } res.Add(x.Key, tmp); } } return res; }