Created
February 26, 2014 20:46
-
-
Save crallen/9238178 to your computer and use it in GitHub Desktop.
Json.NET contract resolver that uses Ruby-style lowercase with underscore naming conventions.
This file contains 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
using Newtonsoft.Json.Serialization; | |
namespace ConsoleApplication3 | |
{ | |
public class SnakeCaseContractResolver : DefaultContractResolver | |
{ | |
protected override string ResolvePropertyName(string propertyName) | |
{ | |
return GetSnakeCase(propertyName); | |
} | |
private string GetSnakeCase(string input) | |
{ | |
if (string.IsNullOrEmpty(input)) | |
return input; | |
var buffer = ""; | |
for (var i = 0; i < input.Length; i++) | |
{ | |
var isLast = (i == input.Length - 1); | |
var isSecondFromLast = (i == input.Length - 2); | |
var curr = input[i]; | |
var next = !isLast ? input[i + 1] : '\0'; | |
var afterNext = !isSecondFromLast && !isLast ? input[i + 2] : '\0'; | |
buffer += char.ToLower(curr); | |
if (!char.IsDigit(curr) && char.IsUpper(next)) | |
{ | |
if (char.IsUpper(curr)) | |
{ | |
if (!isLast && !isSecondFromLast && !char.IsUpper(afterNext)) | |
buffer += "_"; | |
} | |
else | |
buffer += "_"; | |
} | |
if (!char.IsDigit(curr) && char.IsDigit(next)) | |
buffer += "_"; | |
if (char.IsDigit(curr) && !char.IsDigit(next) && !isLast) | |
buffer += "_"; | |
} | |
return buffer; | |
} | |
} | |
} |
I agree, I was using Regex.Replace(input, @"([a-z0-9])([A-Z])", "$1_$2").ToLowerInvariant();
I think the ?<=
in the regex adds unnecessary complexity, am I wrong?
Interesting idea. I'm not sure how the ?<=
(lookbehind) is handled by the regex engine. It's that vs. replacing more data, which at least is guaranteed to be linear time. And yours looks simpler too, so agreed.
Works! Thanks.
Nowadays you don't need a custom contract resolver, just do:
var settings = new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
}
};
Hi Chris,
Thank you for your code! :)
Can you please tell me what is the license for the above code?
Regards,
Andrei
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
PascalCase
andcamelCase
.__HiThere_Guys
becomes__hi_there_guys
.NewVersion3
becomesnew_version3
.3VersionsHere
becomes3_versions_here
, but3rdVersion
becomes3rd_version
.