I have a bunch of enums that I want Json.NET to serialize as camelcased strings. I have the following in my Global.asax.cs file and it's working great:
HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter { CamelCaseText = true });
This makes it so an enum like this:
public enum FavoriteWebSite {
StackOverflow,
GoogleNews
// Etc
}
will serialize to values like "stackOverflow", "googleNews", etc.
However, I have a couple enums that are bitwise masks. To make this a simple example, suppose one looks like this:
public enum Hobbies {
Walking = 0x01,
Biking = 0x02,
// Etc
}
What happens when I serialize instances of this enum depends on what kind of values are in it. For example:
Hobbies set1 = Hobbies.Walking; // Serializes as "walking" -- bad
Hobbies set2 = Hobbies.Walking | Hobbies.Biking; // Serializes as "3" -- good!
I want to override the serialization on this enum to just serialize as an int, while leaving the global setting to use camelcased strings intact.
I tried removing the global configuration so that enums by default are serialized as ints, then adding only [JsonConverter(typeof(StringEnumConverter))]
to the non-bitmask enums. However, this results in PascalCased, rather than CamelCased serialization for those. I didn't see any way to get the CamelCaseText attribute set when using StringEnumConverter in a method decoration like above.
So, to recap, the goal is:
- Have single-value enums be serialized as pascalCased strings.
- Have bitmask enums be serialized as ints.
Thank you!