Default camel case of property names in JSON serialization

后端 未结 7 1098
感情败类
感情败类 2020-12-14 00:35

I have a bunch of classes that will be serialized to JSON at some point and for the sake of following both C# conventions on the back-end and JavaScript conventions on the f

7条回答
  •  难免孤独
    2020-12-14 01:13

    You can use a custom contract resolver:

    class MyContractResolver : DefaultContractResolver
    {
        protected override IList CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            var properties = base.CreateProperties(type, memberSerialization);
    
            foreach (var property in properties)
            {
                property.PropertyName = char.ToLower(property.PropertyName[0]) + string.Join("", property.PropertyName.Skip(1));
            }
    
            return properties;
        }
    }
    

    And use it like:

    class MyClass
    {
        public int MyProperty { get; set; }
        public int MyProperty2 { get; set; }
    }
    
    var json = JsonConvert.SerializeObject(new MyClass(), 
                    Formatting.Indented, 
                    new JsonSerializerSettings { ContractResolver = new MyContractResolver() });
    

提交回复
热议问题