1. 程式人生 > 實用技巧 >Newtonsoft.Json筆記 -ContractResolver

Newtonsoft.Json筆記 -ContractResolver

介紹

CamelCasePropertyNamesContractResolver

Newtonsoft提供的ContractResolver,用於將屬性名轉成駝峰命名格式

//設定序列化時key為駝峰樣式
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();

Demo1:自定義命名規範

需求:序列化時需要將屬性名以下劃線分隔並小寫的格式顯示,如DogName序列化為dog_name
繼承DefaultContractResolver,重寫ResolvePropertyName方法

    public class UnderlineSplitContractResolver : DefaultContractResolver
    {
        protected override string ResolvePropertyName(string propertyName)
        {
            return CamelCaseToUnderlineSplit(propertyName);
        }

        private string CamelCaseToUnderlineSplit(string name)
        {
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < name.Length; i++)
            {
                var ch = name[i];
                if (char.IsUpper(ch) && i > 0)
                {
                    var prev = name[i - 1];
                    if (prev != '_')
                    {
                        if (char.IsUpper(prev))
                        {
                            if (i < name.Length - 1)
                            {
                                var next = name[i + 1];
                                if (char.IsLower(next))
                                {
                                    builder.Append('_');
                                }
                            }
                        }
                        else
                        {
                            builder.Append('_');
                        }
                    }
                }

                builder.Append(char.ToLower(ch));
            }

            return builder.ToString();
        }
    }
    public class Person
    {
        public string Name { get; set; }
        public string DogName { get; set; }
        [JsonProperty("cat_name_1")]
        public string CatName { get; set; }
    }
        static void Main(string[] args)
        {
            JsonSerializerSettings settings = new JsonSerializerSettings
            {
                ContractResolver = new UnderlineSplitContractResolver()
            };
            Person p1 = new Person
            {
                Name = "fan",
                DogName = "ahuang",
                CatName = "nainiu"
            };
            var json = JsonConvert.SerializeObject(p1, settings);
            Console.WriteLine(json);//輸出:{"name":"fan","dog_name":"ahuang","cat_name_1":"nainiu"}
            Console.ReadKey();
        }

Demo2:控制屬性是否序列化