Newtonsoft.Json 添加自定义契约解释器ContractResolver

 

JsonSerializerSettings settings = new JsonSerializerSettings();
settings.ContractResolver = new UnderlineSplitContractResolver();
// JsonConvert.DeserializeObject<dynamic>()
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();

使用"_"分割属性名称

using System.Text;
using Newtonsoft.Json;

namespace MyApp;

public class UnderlineSplitContractResolver : Newtonsoft.Json.Serialization.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; }
    }
       

 

posted @ 2023-07-04 15:50  vba是最好的语言  阅读(150)  评论(0编辑  收藏  举报