I have a class that I cannot change:
public enum MyEnum {
Item1 = 0,
Item2 = 1
}
public class foo {
[JsonConverter(typeof(StringEnumConverter))]
I do not believe you can, as it is part of the definition. You'll have to remove the attribute and add the converter to the serializer settings instead:
var serializerSettings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate,
Converters = new List { new StringEnumConverter() },
ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
};
In that case you can omit it if you don't want to use it. There is one thing I forgot to mention, the converter has to check the type in CanConvert:
public class StringEnumConverter: JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(MyEnum);
}
}
I didn't test the code, but you'll get the idea.