Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save CVertex/d56e56e70e4e2b275680fbd0166a6782 to your computer and use it in GitHub Desktop.
Save CVertex/d56e56e70e4e2b275680fbd0166a6782 to your computer and use it in GitHub Desktop.
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('_') { }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment