其他分享
首页 > 其他分享> > Object 类 Json 序列化 首字母ASCII排序

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;
        }

    }
}

标签:JObject,res,Object,Value,SortedDictionary,首字母,Json,var,序列化
来源: https://blog.csdn.net/gtosky4u/article/details/120953657