1

I'm seeing an issue where I pass into my controller an int that is outside the bounds of my enum but JsonConvert.DeserializeObject still maps to the int passed.

For example I pass in the int 9 to map to the AvatarEnum below and then when I look at the resulting model I see that DefaultAvatar=9, despite AvatarEnum clearly only going up to 5

I have this basic enum:

public enum AvatarEnum : int
{
    Unknown = 0,
    Balloon = 1,
    Flower = 2,
    Sand = 3,
    Bubbles = 4,
    Seaweed = 5
}

Simple model that contains the enum:

internal class DefaultAvatarModel
{
    public AvatarEnum DefaultAvatar { get; set; }
}

The JSON deserialization:

try
{
    avatarModel = JsonConvert.DeserializeObject<DefaultAvatarModel>(jsonMessage);
}
catch (JsonSerializationException)
{
    return Request.CreateResponse(HttpStatusCode.BadRequest, "Bad JSON request.");
}

So I pass in:

jsonMessage = "{\"DefaultAvatar\":\"9\"}"

And the result is:

avatarModel.DefaultAvatar == 9
pflous
  • 573
  • 6
  • 17
  • 2
    That's not an issue, that's how .NET handles enums. See [How can I ignore unknown enum values during json deserialization?](http://stackoverflow.com/questions/22752075/how-can-i-ignore-unknown-enum-values-during-json-deserialization) and [Why does casting int to invalid enum value NOT throw exception?](http://stackoverflow.com/questions/6413804/why-does-casting-int-to-invalid-enum-value-not-throw-exception). – CodeCaster Oct 14 '16 at 15:04
  • http://stackoverflow.com/questions/6413804/why-does-casting-int-to-invalid-enum-value-not-throw-exception – EJoshuaS - Stand with Ukraine Oct 14 '16 at 15:07
  • 1
    @CodeCaster Oh wow thanks [Why does casting int to invalid enum value NOT throw exception?](http://stackoverflow.com/questions/6413804/why-does-casting-int-to-invalid-enum-value-not-throw-exception) really sheds some light on my issue – pflous Oct 14 '16 at 15:09

0 Answers0