Skip to content

Instantly share code, notes, and snippets.

@occluder
Created October 19, 2023 17:58
Show Gist options
  • Save occluder/6a1cc6976dbefb3bf4d5e983192a566a to your computer and use it in GitHub Desktop.
Save occluder/6a1cc6976dbefb3bf4d5e983192a566a to your computer and use it in GitHub Desktop.
Snake case naming policy for C# 's System.Text.Json.JsonSerializer
public class SnakeCaseNamingPolicy : JsonNamingPolicy
{
public override string ConvertName(string name)
{
const char underscore = '_';
ReadOnlySpan<char> chars = name;
Span<char> replacement = stackalloc char[chars.Length * 2];
int i = 1;
int offset = 0;
replacement[0] = char.ToLower(chars[0]);
for (; i < chars.Length; i++)
{
char c = chars[i];
if (char.IsUpper(c))
{
replacement[i + offset++] = underscore;
replacement[i + offset] = char.ToLower(c);
}
else
{
replacement[i + offset] = c;
}
}
return replacement[..(i + offset)].ToString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment