C# JSON.NET convention that follows Ruby property naming conventions?

Solution 1:

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.

Solution 2:

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(); 
        }
    }

Solution 3:

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 attribute
contractResolver.NamingStrategy = new SnakeCaseNamingStrategy(true, false);

Solution 4:

This one worked for me

var settings = new JsonSerializerSettings
{
    ContractResolver = new PascalCaseToUnderscoreContractResolver()
};
var rawJson = "{ test_property:'test' }"
var myObject = JsonConvert.DeserializeObject<MyObjectType>(rawJson, settings);

Using Humanizer function "Underscore"

https://www.nuget.org/packages/Humanizer/1.37.7

http://humanizr.net/#underscore

public class PascalCaseToUnderscoreContractResolver : DefaultContractResolver
{
    protected override string ResolvePropertyName(string propertyName) => propertyName.Underscore();
}

MyObjectType class

public Class MyObjectType
{
    public string TestProperty {get;set;}
}