Created
October 19, 2023 17:58
-
-
Save occluder/6a1cc6976dbefb3bf4d5e983192a566a to your computer and use it in GitHub Desktop.
Snake case naming policy for C# 's System.Text.Json.JsonSerializer
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
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