Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Snake case (underscore separated) property name resolver for Newtonsoft.Json library
public class DeliminatorSeparatedPropertyNamesContractResolver : DefaultContractResolver
{
private readonly string _separator;
protected DeliminatorSeparatedPropertyNamesContractResolver(char separator) : base(true)
{
_separator = separator.ToString();
}
protected override string ResolvePropertyName(string propertyName)
{
var parts = new List<string>();
var currentWord = new StringBuilder();
foreach (var c in propertyName)
{
if (char.IsUpper(c) && currentWord.Length > 0)
{
parts.Add(currentWord.ToString());
currentWord.Clear();
}
currentWord.Append(char.ToLower(c));
}
if (currentWord.Length > 0)
{
parts.Add(currentWord.ToString());
}
return string.Join(_separator, parts.ToArray());
}
}
public class SnakeCasePropertyNamesContractResolver : DeliminatorSeparatedPropertyNamesContractResolver
{
public SnakeCasePropertyNamesContractResolver() : base('_') { }
}
@kbirger

This comment has been minimized.

Show comment
Hide comment
@kbirger

kbirger Jan 2, 2014

What's the license on this?

kbirger commented Jan 2, 2014

What's the license on this?

@RedactedHash

This comment has been minimized.

Show comment
Hide comment
@RedactedHash

RedactedHash Oct 12, 2015

I would recommend this instead...

    for (int j = propertyName.Length - 1; j > 0; j--)
        if (j > 0 && char.IsUpper(propertyName[j]))
            propertyName = propertyName.Insert(j, separator);
    return propertyName.ToLower();

RedactedHash commented Oct 12, 2015

I would recommend this instead...

    for (int j = propertyName.Length - 1; j > 0; j--)
        if (j > 0 && char.IsUpper(propertyName[j]))
            propertyName = propertyName.Insert(j, separator);
    return propertyName.ToLower();
@RokitSalad

This comment has been minimized.

Show comment
Hide comment
@RokitSalad

RokitSalad Oct 11, 2016

Taking numbers into account...

for (int j = propertyName.Length - 1; j > 0; j--)
if ((j > 0 && char.IsUpper(propertyName[j])) || (j > 0 && char.IsNumber(propertyName[j]) && !char.IsNumber(propertyName[j-1])))
propertyName = propertyName.Insert(j, "_");
return propertyName.ToLower();

RokitSalad commented Oct 11, 2016

Taking numbers into account...

for (int j = propertyName.Length - 1; j > 0; j--)
if ((j > 0 && char.IsUpper(propertyName[j])) || (j > 0 && char.IsNumber(propertyName[j]) && !char.IsNumber(propertyName[j-1])))
propertyName = propertyName.Insert(j, "_");
return propertyName.ToLower();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment