This is just a guess, and I haven't tested it.
I looked at the documentation for EnumMemberAttribute
, and it says:
To use EnumMemberAttribute
, create an enumeration and apply the DataContractAttribute
attribute to the enumeration. Then apply the EnumMemberAttribute
attribute to each member that needs to be in the serialization stream.
That's for the DataContractSerializer
, of course, but I'm thinking perhaps JSON.net takes that same rule into account?
I'd try applying [DataContract]
to the enum
.
[DataContract]
public enum FilterOperator
{
[EnumMember(Value = "eq")]
Equals,
[EnumMember(Value = "gt")]
GreaterThan,
[EnumMember(Value = "lt")]
LessThan,
[EnumMember(Value = "in")]
In,
[EnumMember(Value = "like")]
Like
}
It seems arbitrary, and redundant. And I know JSON.net doesn't typically depend on that sort of thing, but maybe in this case it does?
I'm also noticing that it appears the DataContractSerializer
ignores elements without [EnumMember]
if [DataContract]
is present, so it might have to be this way for backwards compatibility. Again, not super logical. But that's all I've got.
Edit: In true developer fashion, rather than just testing this, I went into the source code. The part that reads the EnumMemberAttribute
can be found here on line 55, and it does this:
n2 = f.GetCustomAttributes(typeof(EnumMemberAttribute), true)
.Cast<EnumMemberAttribute>()
.Select(a => a.Value)
.SingleOrDefault() ?? f.Name;
That makes me think that what you've got should be working.
Edit 2:
Alright, so this is odd. I just tried it myself and found it working.
public enum FilterOperator
{
[EnumMember(Value = "eq")]
Equals,
[EnumMember(Value = "gt")]
GreaterThan,
[EnumMember(Value = "lt")]
LessThan,
[EnumMember(Value = "in")]
In,
[EnumMember(Value = "like")]
Like
}
public class GridFilter
{
[JsonProperty("operator")]
[JsonConverter(typeof(StringEnumConverter))]
public FilterOperator Operator { get; set; }
}
[TestMethod]
public void enumTest()
{
GridFilter gf = new GridFilter()
{
Operator = FilterOperator.GreaterThan
};
var json = JsonConvert.SerializeObject(gf);
// json yields {"operator":"gt"}
var ret = JsonConvert.DeserializeObject<GridFilter>(json);
// ret.Operator yields FilterOperator.GreaterThan
}