| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | namespace System.Text.Json |
| | | 5 | | { |
| | | 6 | | internal sealed class JsonCamelCaseNamingPolicy : JsonNamingPolicy |
| | | 7 | | { |
| | | 8 | | public override string ConvertName(string name) |
| | 0 | 9 | | { |
| | 0 | 10 | | if (string.IsNullOrEmpty(name) || !char.IsUpper(name[0])) |
| | 0 | 11 | | { |
| | 0 | 12 | | return name; |
| | | 13 | | } |
| | | 14 | | |
| | | 15 | | #if NET |
| | 0 | 16 | | return string.Create(name.Length, name, (chars, name) => |
| | 0 | 17 | | { |
| | 0 | 18 | | name.CopyTo(chars); |
| | 0 | 19 | | FixCasing(chars); |
| | 0 | 20 | | }); |
| | | 21 | | #else |
| | | 22 | | char[] chars = name.ToCharArray(); |
| | | 23 | | FixCasing(chars); |
| | | 24 | | return new string(chars); |
| | | 25 | | #endif |
| | 0 | 26 | | } |
| | | 27 | | |
| | | 28 | | private static void FixCasing(Span<char> chars) |
| | 0 | 29 | | { |
| | 0 | 30 | | for (int i = 0; i < chars.Length; i++) |
| | 0 | 31 | | { |
| | 0 | 32 | | if (i == 1 && !char.IsUpper(chars[i])) |
| | 0 | 33 | | { |
| | 0 | 34 | | break; |
| | | 35 | | } |
| | | 36 | | |
| | 0 | 37 | | bool hasNext = (i + 1 < chars.Length); |
| | | 38 | | |
| | | 39 | | // Stop when next char is already lowercase. |
| | 0 | 40 | | if (i > 0 && hasNext && !char.IsUpper(chars[i + 1])) |
| | 0 | 41 | | { |
| | | 42 | | // If the next char is a space, lowercase current char before exiting. |
| | 0 | 43 | | if (chars[i + 1] == ' ') |
| | 0 | 44 | | { |
| | 0 | 45 | | chars[i] = char.ToLowerInvariant(chars[i]); |
| | 0 | 46 | | } |
| | | 47 | | |
| | 0 | 48 | | break; |
| | | 49 | | } |
| | | 50 | | |
| | 0 | 51 | | chars[i] = char.ToLowerInvariant(chars[i]); |
| | 0 | 52 | | } |
| | 0 | 53 | | } |
| | | 54 | | } |
| | | 55 | | } |