using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; using NaiBa.Util.Extension; namespace NaiBa.Util.Helper { public class JsonHelper { public static bool IsJson(string html) { if (string.IsNullOrEmpty(html)) { return false; } html = html.Trim(); if ((html.StartsWith("{") && html.EndsWith("}")) || // For object (html.StartsWith("[") && html.EndsWith("]"))) // For array { try { var obj = JToken.Parse(html); return true; } catch { return false; } } return false; } public static string JsonAlphabeticaly(string json) { json = json.ParseToString().Trim(); if (json.StartsWith("{")) { var jObj = JObject.Parse(json); JObject result = new JObject(); OrderJson(result, jObj); return result.ToString(); } else { var jArr = JArray.Parse(json); JArray result = new JArray(); foreach (var arr in jArr) { result.Add(new JObject()); OrderJson((JObject)result[result.Count - 1], (JObject)arr); } return result.ToString(); } } public static string SerializeAlphabeticaly(object obj) { return JsonConvert.SerializeObject(obj, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new OrderedContractResolver() }); } public static string TrimJsonp(string json) { return HtmlHelper.TrimJsonp(json); } #region 私有方法 private static void OrderJson(JObject jObj, JObject item) { foreach (var property in item.Children().OrderBy(p => p.Name)) { switch (property.Value.Type.ToString()) { case "Array": var jArr = new JArray(); jObj.Add(property.Name, jArr); for (int i = 0; i < property.Value.Count(); i++) { switch (property.Value[i].Type.ToString()) { case "Object": var obj = new JObject(); jArr.Add(obj); OrderJson(obj, (JObject)property.Value[i]); break; default: jArr.Add(property.Value[i]); break; } } break; case "Object": jObj.Add(property.Name, new JObject()); OrderJson((JObject)jObj[property.Name], (JObject)property.Value); break; default: jObj.Add(property.Name, property.Value); break; } } } #endregion } public class OrderedContractResolver : DefaultContractResolver { protected override IList CreateProperties(Type type, MemberSerialization memberSerialization) { return base.CreateProperties(type, memberSerialization) .OrderBy(p => p.Order ?? int.MaxValue) // Honour any explit ordering first .ThenBy(p => p.PropertyName) .ToList(); } } }