Newtonsoft Json序列化按照字母顺序排序,修改属性名称

    public class Person
    {
        public string Name { get; set; }

        public List<Book> Books { get; set; }

        public int Age { get; set; }

        [Newtonsoft.Json.JsonProperty("4Test")]
        public string FTest { get; set; }

        public string NullTest { get; set; }
    }

    public class Book
    {
        public string BookName { get; set; }
    }
        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;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            Person p1 = new Person();
            List<Book> books = new List<Book>();
            Book b1 = new Book();
            b1.BookName = "哈利波特";

            Book b2 = new Book();
            b2.BookName = "晚景仙踪";

            books.Add(b1);
            books.Add(b2);
            p1.Name = "呸呸呸";
            p1.Age = 13;
            p1.Books = books;
            p1.FTest = "344";

            //序列化并按照字母顺序排序
            Newtonsoft.Json.JsonSerializerSettings setting = new Newtonsoft.Json.JsonSerializerSettings();
            setting.NullValueHandling =Newtonsoft.Json.NullValueHandling.Ignore ;//Null值不序列化
            string json=Newtonsoft.Json.JsonConvert.SerializeObject(p1, Newtonsoft.Json.Formatting.None, setting);
            var a =JObject.Parse(json);
            var target = KeySort(a);
            json = Newtonsoft.Json.JsonConvert.SerializeObject(target);
        }

 

上一篇:使用Newtonsoft.Json操作json


下一篇:Newtonsoft.Json序列化DateTime类型数据