11using System ;
22using System . Linq ;
33using Newtonsoft . Json ;
4+ using Newtonsoft . Json . Converters ;
45
56namespace OpenStack . Serialization
67{
78 /// <summary>
89 /// Attempts to convert a string to an enum using the following resolution strategy:
9- /// <para>1. Use the name of the enum .</para>
10+ /// <para>1. Use StringEnumConverter .</para>
1011 /// <para>2. Use null if the property is nullable.</para>
1112 /// <para>3. Use the Unknown enum value.</para>
1213 /// <para>4. Use the first enum value.</para>
1314 /// </summary>
1415 /// <seealso href="http://stackoverflow.com/a/22755077/808818"/>
1516 /// <exclude />
16- public class TolerantEnumConverter : JsonConverter
17+ public class TolerantEnumConverter : StringEnumConverter
1718 {
1819 /// <inheritdoc/>
1920 public override bool CanConvert ( Type objectType )
@@ -25,20 +26,19 @@ public override bool CanConvert(Type objectType)
2526 /// <inheritdoc/>
2627 public override object ReadJson ( JsonReader reader , Type objectType , object existingValue , JsonSerializer serializer )
2728 {
29+ try
30+ {
31+ return base . ReadJson ( reader , objectType , existingValue , serializer ) ;
32+ }
33+ catch ( JsonSerializationException )
34+ {
35+
36+ }
2837 bool isNullable = IsNullableType ( objectType ) ;
2938 Type enumType = isNullable ? Nullable . GetUnderlyingType ( objectType ) : objectType ;
3039
3140 string [ ] names = Enum . GetNames ( enumType ) ;
3241
33- string enumText = reader . Value . ToString ( ) ;
34-
35- if ( ! string . IsNullOrEmpty ( enumText ) )
36- {
37- string match = names . FirstOrDefault ( n => string . Equals ( n , enumText , StringComparison . OrdinalIgnoreCase ) ) ;
38- if ( match != null )
39- return Enum . Parse ( enumType , match ) ;
40- }
41-
4242 if ( ! isNullable )
4343 {
4444 string defaultName = names . FirstOrDefault ( n => string . Equals ( n , "Unknown" , StringComparison . OrdinalIgnoreCase ) ) ;
0 commit comments