我有一个枚举:

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; }
}

该对象通过WebAPI操作传入,并按预期对“like”和“in”进行反序列化,但不适用于“lg”或“gt”。知道为什么吗?

更新:好吧,“赞”和“参与”工作的原因是它们与枚举名称匹配。将GreaterThan重命名为Gt(etc)是可行的。因此,真正的问题是为什么不使用StringEnumConverter?

最佳答案

好吧,如果希望在类[JsonConverter(typeof(StringEnumConverter))]的上下文之外进行反序列化时使用enum属性,而不是OperatorGridFilter属性,则必须直接将GridFilter属性放置在:

[JsonConverter(typeof(StringEnumConverter))] // Add this
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")] // Remove this
    public FilterOperator Operator { get; set; }
}

关于c# - Json.NET StringEnumConverter并不总是工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28187150/

10-13 05:56