-
Notifications
You must be signed in to change notification settings - Fork 7
/
JsonSnakeCaseNamingPolicy.cs
79 lines (69 loc) · 3.02 KB
/
JsonSnakeCaseNamingPolicy.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
namespace System.Text.Json
{
public class JsonSnakeCaseNamingPolicy : JsonNamingPolicy
{
private readonly string _separator = "_";
public override string ConvertName(string name)
{
if (String.IsNullOrEmpty(name) || String.IsNullOrWhiteSpace(name)) return String.Empty;
ReadOnlySpan<char> spanName = name.Trim();
var stringBuilder = new StringBuilder();
var addCharacter = true;
var isPreviousSpace = false;
var isPreviousSeparator = false;
var isCurrentSpace = false;
var isNextLower = false;
var isNextUpper = false;
var isNextSpace = false;
for (int position = 0; position < spanName.Length; position++)
{
if (position != 0)
{
isCurrentSpace = spanName[position] == 32;
isPreviousSpace = spanName[position - 1] == 32;
isPreviousSeparator = spanName[position - 1] == 95;
if (position + 1 != spanName.Length)
{
isNextLower = spanName[position + 1] > 96 && spanName[position + 1] < 123;
isNextUpper = spanName[position + 1] > 64 && spanName[position + 1] < 91;
isNextSpace = spanName[position + 1] == 32;
}
if ((isCurrentSpace) &&
((isPreviousSpace) ||
(isPreviousSeparator) ||
(isNextUpper) ||
(isNextSpace)))
addCharacter = false;
else
{
var isCurrentUpper = spanName[position] > 64 && spanName[position] < 91;
var isPreviousLower = spanName[position - 1] > 96 && spanName[position - 1] < 123;
var isPreviousNumber = spanName[position - 1] > 47 && spanName[position - 1] < 58;
if ((isCurrentUpper) &&
((isPreviousLower) ||
(isPreviousNumber) ||
(isNextLower) ||
(isNextSpace) ||
(isNextLower && !isPreviousSpace)))
stringBuilder.Append(_separator);
else
{
if ((isCurrentSpace &&
!isPreviousSpace &&
!isNextSpace))
{
stringBuilder.Append(_separator);
addCharacter = false;
}
}
}
}
if (addCharacter)
stringBuilder.Append(spanName[position]);
else
addCharacter = true;
}
return stringBuilder.ToString().ToLower();
}
}
}