C# JSON.NET convention that follows Ruby property naming conventions?
Update - September 2016:
Json.NET 9.0.1 has SnakeCaseNamingStrategy. You can use that to have twitter_screen_name style properties automatically.
Inherit from DefaultContractResolver
and override ResolvePropertyName
to format property names as you'd like.
CamelCasePropertyNamesContractResolver
does a similar global change to property names.
Read this : http://nyqui.st/json-net-newtonsoft-json-lowercase-keys
public class UnderscoreMappingResolver : DefaultContractResolver { protected override string ResolvePropertyName(string propertyName) { return System.Text.RegularExpressions.Regex.Replace( propertyName, @"([A-Z])([A-Z][a-z])|([a-z0-9])([A-Z])", "$1$3_$2$4").ToLower(); } }
As of version 9, a new naming strategy property exists to do this, and it has a built-in SnakeCaseNamingStrategy class. Use the code below and register contractResolver
as SerializerSettings.ContractResolver
.
var contractResolver = new DefaultContractResolver();contractResolver.NamingStrategy = new SnakeCaseNamingStrategy();
That class does not include dictionaries by default, and it does not override any manually-set property values. Those are the two parameters that can be passed in the overload:
// true parameter forces handling of dictionaries// false prevents the serializer from changing anything manually set by an attributecontractResolver.NamingStrategy = new SnakeCaseNamingStrategy(true, false);