I have a class that I cannot change:
public enum MyEnum {
Item1 = 0,
Item2 = 1
}
public class foo {
[JsonConverter(typeof(StringEnumConverter))]
public MyEnum EnumTypes {get; set; }
}
Somewhere down the line JsonConvert.SerializeObject
serializes the object and because of the JsonConverter
attribute, it spits out name of the enum value for the foo.EnumTypes
rather than the number.
Is there anyway to get JsonConvert.SerializeObject
to ignore the attribute on the EnumTypes
property?
To ignore individual properties, use the [JsonIgnore] attribute. You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored.
SerializeObject Method. Serializes the specified object to a JSON string. Serializes the specified object to a JSON string using formatting.
Apply a [JsonIgnore] attribute to the property that you do not want to be serialized.
Return ValueA JSON string representation of the object.
This is possible, but the process is a tad involved.
The basic idea is to create a custom ContractResolver
and override its CreateProperty
method. Something like so:
internal sealed class MyContractResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty( MemberInfo member, MemberSerialization memberSerialization )
{
var property = base.CreateProperty( member, memberSerialization );
if( member.DeclaringType == typeof( foo ) && property.PropertyType == typeof( MyEnum ) )
{
property.Converter = null;
}
return property;
}
}
You'll also need to actually instantiate this class and pass it into your serializer/deserializer. What that looks like depends on exactly how you're doing the serialization, so I can't guarantee a relevant example of how to use it.
If you're just using the static SerializeObject
method:
JsonConvert.SerializeObject( valueToSerialize, new SerializerSettings { ContractResolver = new MyContractResolver() } );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With