C#对类所有属性进行排序并输出Json数据以及对Json数据进行排序
/// <summary> /// 对自定义类进行升序排序,并输出Json字符串 /// </summary> /// <example> /// string json=JsonConvert.SerializeObject(new 自定义类名(){...}, new JsonSerializerSettings { ContractResolver = new SortContractResolver() }); /// </example> /// <remarks> /// 需要Newtonsoft.Json的包 /// </remarks> public class SortContractResolver : DefaultContractResolver { protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization) { IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization); return properties.OrderBy(x => x.PropertyName).ToList(); } } /// <summary> /// 对自定义类进行升序排序 /// </summary> /// <param name="obj">自定义类对象</param> /// <returns></returns> /// <example> /// string json = JsonConvert.SerializeObject(GetSorObject(new 自定义类名(){...})); /// </example> /// <remarks> /// 需要Newtonsoft.Json的包 /// </remarks> private static dynamic GetSorObject(Object obj) { if (obj is JArray) { var list = new List<dynamic>(); foreach (var item in (obj as JArray)) { list.Add(GetSorObject(item)); } return list; } else { var paramDic = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(JsonConvert.SerializeObject(obj)); var sortedDic = new SortedDictionary<string, dynamic>(); for (int i = 0; i < paramDic.Count; i++) { if (paramDic.ElementAt(i).Value is JArray || paramDic.ElementAt(i).Value is JObject) { sortedDic.Add(paramDic.ElementAt(i).Key, GetSorObject(paramDic.ElementAt(i).Value)); } else { sortedDic.Add(paramDic.ElementAt(i).Key, paramDic.ElementAt(i).Value); } } return sortedDic; } } /// <summary> /// 对Json数据进行升序或降序 /// </summary> /// <param name="json">Json数据</param> /// <returns></returns> /// <example> /// string resultJson=StortJson(json); /// </example> /// <remarks> /// 需要Newtonsoft.Json的包 /// 只能对根节点下的子节点进行排序,孙子节点不能被排序 /// </remarks> public string StortJson(string json) { var dic = JsonConvert.DeserializeObject<SortedDictionary<string, object>>(json); SortedDictionary<string, object> keyValues = new SortedDictionary<string, object>(dic); //var result = keyValues.OrderBy(m => m.Key);//升序 把Key换成Value 就是对Value进行排序 var result = keyValues.OrderByDescending(m => m.Key);//降序 //Dictionary<string, object> resultDic = new Dictionary<string, object>(); result.ToDictionary(x => x.Key, x => x.Value); //foreach (var item in result) //{ // resultDic.Add(item.Key, item.Value); //} //简化为如下代码 Dictionary<string, object> resultDic =result.ToDictionary(x => x.Key, x => x.Value); return JsonConvert.SerializeObject(resultDic); }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 2 本地部署DeepSeek模型构建本地知识库+联网搜索详细步骤