Allow JsonConverterAttribute to be applied to an Enum (dotnet/corefx#39790)
authorSteve Harter <steveharter@users.noreply.github.com>
Fri, 26 Jul 2019 17:20:30 +0000 (12:20 -0500)
committerGitHub <noreply@github.com>
Fri, 26 Jul 2019 17:20:30 +0000 (12:20 -0500)
Commit migrated from https://github.com/dotnet/corefx/commit/de61fb206e61f105f657ca01b1244580cc9e1e77

src/libraries/System.Text.Json/ref/System.Text.Json.cs
src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonConverterAttribute.cs
src/libraries/System.Text.Json/tests/Serialization/EnumConverterTests.cs

index 36a42ce..c9560f4 100644 (file)
@@ -459,7 +459,7 @@ namespace System.Text.Json.Serialization
         internal JsonConverter() { }
         public abstract bool CanConvert(System.Type typeToConvert);
     }
-    [System.AttributeUsageAttribute(System.AttributeTargets.Class | System.AttributeTargets.Property | System.AttributeTargets.Struct, AllowMultiple=false)]
+    [System.AttributeUsageAttribute(System.AttributeTargets.Class | System.AttributeTargets.Enum | System.AttributeTargets.Property | System.AttributeTargets.Struct, AllowMultiple=false)]
     public partial class JsonConverterAttribute : System.Text.Json.Serialization.JsonAttribute
     {
         protected JsonConverterAttribute() { }
index fd08c8b..2d0573a 100644 (file)
@@ -14,7 +14,7 @@ namespace System.Text.Json.Serialization
     /// <see cref="JsonSerializerOptions.Converters"/> or there is another <see cref="JsonConverterAttribute"/> on a property
     /// of the same type.
     /// </remarks>
-    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false)]
+    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Property | AttributeTargets.Struct, AllowMultiple = false)]
     public class JsonConverterAttribute : JsonAttribute
     {
         /// <summary>
index 17447fd..3c15d9d 100644 (file)
@@ -165,5 +165,25 @@ namespace System.Text.Json.Serialization.Tests
             public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options)
                 => s_stringEnumConverter.CreateConverter(typeToConvert, options);
         }
+
+        [JsonConverter(typeof(JsonStringEnumConverter))]
+        private enum MyCustomEnum
+        {
+            First = 1,
+            Second =2
+        }
+
+        [Fact]
+        public void EnumWithConverterAttribute()
+        {
+            string json = JsonSerializer.Serialize(MyCustomEnum.Second);
+            Assert.Equal(@"""Second""", json);
+
+            MyCustomEnum obj = JsonSerializer.Deserialize<MyCustomEnum>("\"Second\"");
+            Assert.Equal(MyCustomEnum.Second, obj);
+
+            obj = JsonSerializer.Deserialize<MyCustomEnum>("2");
+            Assert.Equal(MyCustomEnum.Second, obj);
+        }
     }
 }