JSON字串排序

  • 915
  • 0

JSON字串排序

如果想要對JSON裡面的欄位進行由小到大排序,如

{"A":"111","C":"222","B":"333"}

排序為

{"A":"111","B":"333","C":"222"}

之前都是參考這篇

 

但是遇到了像這樣的JSON物件

{
  "A": "111",
  "C": "222",
  "B": [
    {
      "CC": "我是CC"
      "AA": "我是AA",
    },
    {
      "BB": "我是BB",
      "DD": "我是DD"
    }
  ]
}

如果用上面的程式去跑,會產生這樣結果

{
  "A": "111",
  "B": [
    {
      "CC": "我是CC",
      "AA": "我是AA"
    },
    {
      "BB": "我是BB",
      "DD": "我是DD"
    }
  ],
  "C": "222"
}

hmm.....ABCD是排序了沒錯,但是B裡面的AA、CC卻沒有

那就動手改一下程式吧

        /// <summary>
        /// 排序JObject
        /// </summary>
        /// <param name="Obj"></param>
        public static void Sort(JObject Obj)
        {
            var properties = Obj.Properties().ToList();
            foreach (var prop in properties) //如果不先清空,等等的Obj.Add會報錯
            {
                prop.Remove();
            }

            foreach (var prop in properties.OrderBy(p => p.Name))
            {
                Obj.Add(prop);
                if (prop.Value is JObject)
                    Sort((JObject)prop.Value);
                else if (prop.Value is JArray)
                    prop.Value = SortJArray((JArray)prop.Value);
            }
        }
        /// <summary>
        /// 排序JArray
        /// </summary>
        /// <param name="Obj"></param>
        public static JArray SortJArray(JArray Obj)
        {
            JArray SortJArray = new JArray();
            Dictionary<string, string> dict;
            foreach (JObject o in Obj.Children<JObject>())
            {
                dict = new Dictionary<string, string>();
                foreach (JProperty p in o.Properties())
                {
                    dict.Add(p.Name, (string)p.Value);
                }
                var sortdict = dict.OrderBy(x => x.Key).ToDictionary(q => q.Key, p => p.Value);
                JToken jtoken = JToken.FromObject(sortdict);
                SortJArray.Add(jtoken);
            }           
            return SortJArray;
        }

想法是,將每個JArray的值填入Dictionary,再由Dictionary排序

最後將prop取出轉成JToken存入新的JArray再做回傳

 

打完,收工~