Web Api incorrectly deserializes enumeration list

So, I am using a web API controller to receive JSON requests. This is a mapping to a model object that includes a list of enumerations. The problem I ran into is that if the JSON contains an invalid value, it does not seem to deserialize correctly. I would expect the invalid value to be mapped to the value type 0 in my enumeration list, however this does not happen.

There are three main cases that I have highlighted: if JSON is in the form

    ...
    "MyEnumList":["IncorrectEnum", "One", "Two"]
    ...

The value is not displayed at all, and I just get a list with two valid values. However, if I put this JSON:

   ...
   "MyEnumList":["123", "One", "Two"]
   ...

I get a list with 3 objects, where the first object is of type "MyEnum" and has a value of 123, although this is not defined in my listing. The same thing happens if I put this JSON syntax:

   ...
   "MyEnumList":[123, "One", "Two"]
   ...

Can someone explain what is happening here, and how can I guarantee that the values ​​are always matched against a valid type?

For reference: A model object that contains a list of my enumeration:

    public class MyClass
    {
       public List<myEnum> MyEnumList { get; set; }
    }

and simple listing:

    public enum myEnum 
    {
       Zero = 0,
       One = 1,
       Two = 2
    }
+4
source share
1 answer

, 123 , 123, Json.Net. , # . , :

class Program
{
    static void Main(string[] args)
    {
        // Direct cast from integer -- no error here
        MyEnum x = (MyEnum)123;
        Console.WriteLine(x);

        // Parsing a numeric string -- no error here either
        MyEnum y = (MyEnum)Enum.Parse(typeof(MyEnum), "456");
        Console.WriteLine(y);
    }

    public enum MyEnum
    {
        Zero = 0,
        One = 1,
        Two = 2
    }
}

, , , Json.Net Enum.Parse . , . , ( ).

, enum, JsonConverter, (, , ). , . (, , .)

class StrictEnumConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType.BaseType == typeof(Enum));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JToken token = JToken.Load(reader);

        try
        {
            // We're only interested in integers or strings;
            // all other token types should fall through
            if (token.Type == JTokenType.Integer ||
                token.Type == JTokenType.String)
            {
                // Get the string representation of the token
                // and check if it is numeric
                string s = token.ToString();
                int i;
                if (int.TryParse(s, out i))
                {
                    // If the token is numeric, try to find a matching
                    // name from the enum. If it works, convert it into
                    // the actual enum value; otherwise punt.
                    string name = Enum.GetName(objectType, i);
                    if (name != null)
                        return Enum.Parse(objectType, name);
                }
                else
                {
                    // We've got a non-numeric value, so try to parse it
                    // as is (case insensitive). If this doesn't work,
                    // it will throw an ArgumentException.
                    return Enum.Parse(objectType, s, true);
                }
            }
        }
        catch (ArgumentException)
        {
            // Eat the exception and fall through
        }

        // We got a bad value, so return the first value from the enum as
        // a default. Alternatively, you could throw an exception here to
        // halt the deserialization.
        IEnumerator en = Enum.GetValues(objectType).GetEnumerator();
        en.MoveNext();
        return en.Current;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue(value.ToString());
    }
}

, :

class Program
{
    static void Main(string[] args)
    {
        // The first 12 values should deserialize to correct values;
        // the last 7 should all be forced to MyEnum.Zero.
        string json = @"
        {
            ""MyEnumList"":
            [
                ""Zero"", 
                ""One"", 
                ""Two"", 
                0,
                1,
                2,
                ""zero"",
                ""one"",
                ""two"",
                ""0"",
                ""1"",
                ""2"",
                ""BAD"", 
                ""123"", 
                123, 
                1.0,
                null,
                false,
                true
            ]
        }";

        MyClass obj = JsonConvert.DeserializeObject<MyClass>(json, 
                                                   new StrictEnumConverter());
        foreach (MyEnum e in obj.MyEnumList)
        {
            Console.WriteLine(e.ToString());
        }
    }

    public enum MyEnum
    {
        Zero = 0,
        One = 1,
        Two = 2
    }

    public class MyClass
    {
        public List<MyEnum> MyEnumList { get; set; }
    }
}

:

Zero
One
Two
Zero
One
Two
Zero
One
Two
Zero
One
Two
Zero
Zero
Zero
Zero
Zero
Zero
Zero

, Web API, Application_Start() Global.asax.cs:

JsonSerializerSettings settings = GlobalConfiguration.Configuration.Formatters 
                                  .JsonFormatter.SerializerSettings;
settings.Converters.Add(new StrictEnumConverter());
+6

All Articles