There is no way to make CamelCasePropertyNamesContractResolver
convert strings to camel case the way you want, but you can easily write your own ContractResolver
.
I used the PascalCase transform in a CsCss project. After a little adaptation, here is the result:
public enum IdentifierCase { Camel, Pascal, } public class CustomPropertyNamesContractResolver : DefaultContractResolver { private static readonly CultureInfo Culture = CultureInfo.InvariantCulture; public CustomPropertyNamesContractResolver (bool shareCache = false) : base(shareCache) { Case = IdentifierCase.Camel; PreserveUnderscores = true; } public IdentifierCase Case { get; set; } public bool PreserveUnderscores { get; set; } protected override string ResolvePropertyName (string propertyName) { return ChangeCase(propertyName); } private string ChangeCase (string s) { var sb = new StringBuilder(s.Length); bool isNextUpper = Case == IdentifierCase.Pascal, isPrevLower = false; foreach (var c in s) { if (c == '_') { if (PreserveUnderscores) sb.Append(c); isNextUpper = true; } else { sb.Append(isNextUpper ? char.ToUpper(c, Culture) : isPrevLower ? c : char.ToLower(c, Culture)); isNextUpper = false; isPrevLower = char.IsLower(c); } } return sb.ToString(); }
This converter supports both PascalCase
and camelCase
. It seems to convert property names the way you expect.
I left the oroginal ToCamelCase
function from Json.NET for reference.
Program Example:
internal class Program { private static void Main () { var obj = new Dictionary<string, string> { { "SessionID", "123456" }, { "HTTP_VERB", "POST" }, { "HTTPVERSION", "1" }, }; var settings = new JsonSerializerSettings { Formatting = Formatting.Indented, ContractResolver = new CustomPropertyNamesContractResolver() }; string strCamel = JsonConvert.SerializeObject(obj, settings); Console.WriteLine("camelCase: \n" + strCamel); Console.WriteLine(strCamel.Contains("httP_VERB") ? "Something is wrong with this camel case" : "Success"); settings.ContractResolver = new CustomPropertyNamesContractResolver { Case = IdentifierCase.Pascal, PreserveUnderscores = false, }; string strPascal = JsonConvert.SerializeObject(obj, settings); Console.WriteLine("PascalCase: \n" + strPascal); Console.ReadKey(); } }
Output:
camelCase: { "sessionId": "123456", "http_Verb": "POST", "httpversion": "1" } Success PascalCase: { "SessionId": "123456", "HttpVerb": "POST", "Httpversion": "1" }
source share