-Added CamelCaseText to StringEnumConverter

This commit is contained in:
JamesNK
2010-12-19 00:49:35 +00:00
parent 5ccd826951
commit c046ac36f9
5 changed files with 51 additions and 13 deletions
@@ -34,6 +34,11 @@ namespace Newtonsoft.Json.Converters
/// </summary>
public class StringEnumConverter : JsonConverter
{
/// <summary>
/// Gets or sets a value indicating whether the written enum text should be camel case.
/// </summary>
/// <value><c>true</c> if the written enum text will be camel case; otherwise, <c>false</c>.</value>
public bool CamelCaseText { get; set; }
/// <summary>
/// Writes the JSON representation of the object.
@@ -53,9 +58,18 @@ namespace Newtonsoft.Json.Converters
string enumName = e.ToString("G");
if (char.IsNumber(enumName[0]) || enumName[0] == '-')
{
// enum value didn't have an option against it
// fallback to writing number value
writer.WriteValue(value);
}
else
{
if (CamelCaseText)
enumName = StringUtils.ToCamelCase(enumName);
writer.WriteValue(enumName);
}
}
/// <summary>
@@ -24,6 +24,7 @@
#endregion
using System.Globalization;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Serialization
{
@@ -48,17 +49,7 @@ namespace Newtonsoft.Json.Serialization
protected override string ResolvePropertyName(string propertyName)
{
// lower case the first letter of the passed in name
if (string.IsNullOrEmpty(propertyName))
return propertyName;
if (!char.IsUpper(propertyName[0]))
return propertyName;
string camelCaseName = char.ToLower(propertyName[0], CultureInfo.InvariantCulture).ToString(CultureInfo.InvariantCulture);
if (propertyName.Length > 1)
camelCaseName += propertyName.Substring(1);
return camelCaseName;
return StringUtils.ToCamelCase(propertyName);
}
}
}
@@ -369,5 +369,20 @@ namespace Newtonsoft.Json.Utilities
return caseSensitiveResults.SingleOrDefault();
}
}
public static string ToCamelCase(string s)
{
if (string.IsNullOrEmpty(s))
return s;
if (!char.IsUpper(s[0]))
return s;
string camelCase = char.ToLower(s[0], CultureInfo.InvariantCulture).ToString(CultureInfo.InvariantCulture);
if (s.Length > 1)
camelCase += s.Substring(1);
return camelCase;
}
}
}