Created
June 23, 2011 13:09
-
-
Save roryf/1042502 to your computer and use it in GitHub Desktop.
Snake case (underscore separated) property name resolver for Newtonsoft.Json library
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SnakeCasePropertyNamesContractResolver : DeliminatorSeparatedPropertyNamesContractResolver | |
{ | |
public SnakeCasePropertyNamesContractResolver() : base('_') { } | |
} |
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();
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
What's the license on this?