Object 类 Json 序列化 首字母ASCII排序

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Linq;
namespace Vip.System.Model
{
    public class JsonUtils
    {
        /// <summary>
        /// Json 序列化
        /// 1. 按首字母排序
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string GetSortStrJson(object obj)
        {
            JsonSerializerSettings setting = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
            string strData = JsonConvert.SerializeObject(obj, Formatting.None, setting);
            JObject jobject = JObject.Parse(strData);
            SortedDictionary<string, object> target = KeySort(jobject);
            string jsonStr = JsonConvert.SerializeObject(target);
            return jsonStr;
        }


        /// <summary>
        /// 排序
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public 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;
        }

    }
}

上一篇:CodeGo.net>如何手动添加项目到Repeater控件


下一篇:数据绑定控件之Repeater