FindEnumValue assumes enums are always of type int

218 views
Skip to first unread message

Alex Angas

unread,
Nov 13, 2013, 1:52:13 AM11/13/13
to rest...@googlegroups.com
Howdy,

I'm getting an exception when deserializing a JSON response containing an enum of type short/Int16. Stack trace is:

[ArgumentException: Enum underlying type and the object must be same type or object must be a String. Type passed in was 'System.Int32'; the enum underlying type was 'System.Int16'.]
   System.Enum.IsDefined(Type enumType, Object value) +10371040
   RestSharp.Extensions.ReflectionExtensions.FindEnumValue(Type type, String value, CultureInfo culture) +375
   RestSharp.Deserializers.JsonDeserializer.ConvertValue(Type type, Object value) +536
   RestSharp.Deserializers.JsonDeserializer.Map(Object target, IDictionary`2 data) +1244
   RestSharp.Deserializers.JsonDeserializer.CreateAndMap(Type type, Object element) +132
   RestSharp.Deserializers.JsonDeserializer.ConvertValue(Type type, Object value) +2329
   RestSharp.Deserializers.JsonDeserializer.BuildList(Type type, Object parent) +1205
   RestSharp.Deserializers.JsonDeserializer.Deserialize(IRestResponse response) +695
   RestSharp.RestClient.Deserialize(IRestRequest request, IRestResponse raw) +1035

It looks to me that this is because enums can be any integral type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However the code assumes they will always be an int:

    int enumValueAsInt;
    if (Int32.TryParse(value, out enumValueAsInt) && Enum.IsDefined(type, enumValueAsInt))

I'm happy to help fix this, although it's not clear to me what the solution should be.

One improvement to at least allow shorts through could be to remove the call causing the exception... Is Enum.IsDefined necessary given that the values are retrieved from Enum.GetValues earlier in the method?

Cheers,

Alex.

Andrew Young

unread,
Nov 13, 2013, 2:37:44 AM11/13/13
to rest...@googlegroups.com, Alex Angas
I believe you will have to use Enum.GetUnderlyingType() before knowing which overload of Enum.IsDefined() to call. Submit a pull with the fix along with tests.

--
Andrew Young
Sent with Airmail
--
You received this message because you are subscribed to the Google Groups "RestSharp" group.
To unsubscribe from this group and stop receiving emails from it, send an email to restsharp+...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
Reply all
Reply to author
Forward
0 new messages