Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add JsonEnumMemberNameAttribute. #105032

Merged
merged 14 commits into from
Jul 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/libraries/System.Text.Json/ref/System.Text.Json.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1164,6 +1164,12 @@ public JsonStringEnumConverter(System.Text.Json.JsonNamingPolicy? namingPolicy =
public sealed override bool CanConvert(System.Type typeToConvert) { throw null; }
public sealed override System.Text.Json.Serialization.JsonConverter CreateConverter(System.Type typeToConvert, System.Text.Json.JsonSerializerOptions options) { throw null; }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Field, AllowMultiple=false)]
public partial class JsonStringEnumMemberNameAttribute : System.Attribute
{
public JsonStringEnumMemberNameAttribute(string name) { }
public string Name { get { throw null; } }
}
public enum JsonUnknownDerivedTypeHandling
{
FailSerialization = 0,
Expand Down
4 changes: 2 additions & 2 deletions src/libraries/System.Text.Json/src/Resources/Strings.resx
Original file line number Diff line number Diff line change
Expand Up @@ -231,8 +231,8 @@
<data name="InvalidCharacterWithinString" xml:space="preserve">
<value>'{0}' is invalid within a JSON string. The string should be correctly escaped.</value>
</data>
<data name="InvalidEnumTypeWithSpecialChar" xml:space="preserve">
<value>Enum type '{0}' uses unsupported identifer name '{1}'.</value>
<data name="UnsupportedEnumIdentifier" xml:space="preserve">
<value>Enum type '{0}' uses unsupported identifier '{1}'. It must not be null, empty, or containing leading or trailing whitespace. Flags enums must additionally not contain commas.</value>
</data>
<data name="InvalidEndOfJsonNonPrimitive" xml:space="preserve">
<value>'{0}' is an invalid token type for the end of the JSON payload. Expected either 'EndArray' or 'EndObject'.</value>
Expand Down
1 change: 1 addition & 0 deletions src/libraries/System.Text.Json/src/System.Text.Json.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,7 @@ The System.Text.Json library is built-in as part of the shared framework in .NET
<Compile Include="System\Text\Json\Serialization\JsonSerializerOptions.Converters.cs" />
<Compile Include="System\Text\Json\Serialization\JsonSerializerOptions.cs" />
<Compile Include="System\Text\Json\Serialization\JsonStringEnumConverter.cs" />
<Compile Include="System\Text\Json\Serialization\JsonStringEnumMemberNameAttribute.cs" />
<Compile Include="System\Text\Json\Serialization\Metadata\FSharpCoreReflectionProxy.cs" />
<Compile Include="System\Text\Json\Serialization\Metadata\JsonCollectionInfoValuesOfTCollection.cs" />
<Compile Include="System\Text\Json\Serialization\Metadata\JsonMetadataServices.Collections.cs" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,11 +95,11 @@ private static bool HasCustomAttributeWithName(this MemberInfo memberInfo, strin
/// Polyfill for BindingFlags.DoNotWrapExceptions
/// </summary>
public static object? CreateInstanceNoWrapExceptions(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicConstructors)] this Type type,
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] this Type type,
Type[] parameterTypes,
object?[] parameters)
{
ConstructorInfo ctorInfo = type.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, parameterTypes, null)!;
ConstructorInfo ctorInfo = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, parameterTypes, null)!;
#if NET
return ctorInfo.Invoke(BindingFlags.DoNotWrapExceptions, null, parameters, null);
#else
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,7 @@ public static bool HasAllSet(this BitArray bitArray)
/// Gets a Regex instance for recognizing integer representations of enums.
/// </summary>
public static readonly Regex IntegerRegex = CreateIntegerRegex();
private const string IntegerRegexPattern = @"^\s*(\+|\-)?[0-9]+\s*$";
private const string IntegerRegexPattern = @"^\s*(?:\+|\-)?[0-9]+\s*$";
eiriktsarpalis marked this conversation as resolved.
Show resolved Hide resolved
private const int IntegerRegexTimeoutMs = 200;

#if NET
Expand Down

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@

using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json.Reflection;

namespace System.Text.Json.Serialization.Converters
{
[RequiresDynamicCode(JsonSerializer.SerializationRequiresDynamicCodeMessage)]
internal sealed class EnumConverterFactory : JsonConverterFactory
{
[RequiresDynamicCode(JsonSerializer.SerializationRequiresDynamicCodeMessage)]
public EnumConverterFactory()
{
}
Expand All @@ -18,23 +19,48 @@ public override bool CanConvert(Type type)
return type.IsEnum;
}

public static bool IsSupportedTypeCode(TypeCode typeCode)
{
return typeCode is TypeCode.SByte or TypeCode.Int16 or TypeCode.Int32 or TypeCode.Int64
or TypeCode.Byte or TypeCode.UInt16 or TypeCode.UInt32 or TypeCode.UInt64;
}

[SuppressMessage("AOT", "IL3050:Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.",
Justification = "The constructor has been annotated with RequiredDynamicCodeAttribute.")]
public override JsonConverter CreateConverter(Type type, JsonSerializerOptions options)
{
Debug.Assert(CanConvert(type));
return Create(type, EnumConverterOptions.AllowNumbers, namingPolicy: null, options);
}

internal static JsonConverter Create(Type enumType, EnumConverterOptions converterOptions, JsonNamingPolicy? namingPolicy, JsonSerializerOptions options)
public static JsonConverter<T> Create<T>(EnumConverterOptions converterOptions, JsonSerializerOptions options, JsonNamingPolicy? namingPolicy = null)
where T : struct, Enum
{
return (JsonConverter)Activator.CreateInstance(
GetEnumConverterType(enumType),
new object?[] { converterOptions, namingPolicy, options })!;
if (!IsSupportedTypeCode(Type.GetTypeCode(typeof(T))))
{
// Char-backed enums are valid in IL and F# but are not supported by System.Text.Json.
return new UnsupportedTypeConverter<T>();
}

return new EnumConverter<T>(converterOptions, namingPolicy, options);
}

[RequiresDynamicCode(JsonSerializer.SerializationRequiresDynamicCodeMessage)]
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:UnrecognizedReflectionPattern",
Justification = "'EnumConverter<T> where T : struct' implies 'T : new()', so the trimmer is warning calling MakeGenericType here because enumType's constructors are not annotated. " +
"But EnumConverter doesn't call new T(), so this is safe.")]
[return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)]
private static Type GetEnumConverterType(Type enumType) => typeof(EnumConverter<>).MakeGenericType(enumType);
public static JsonConverter Create(Type enumType, EnumConverterOptions converterOptions, JsonNamingPolicy? namingPolicy, JsonSerializerOptions options)
{
if (!IsSupportedTypeCode(Type.GetTypeCode(enumType)))
{
// Char-backed enums are valid in IL and F# but are not supported by System.Text.Json.
return UnsupportedTypeConverterFactory.CreateUnsupportedConverterForType(enumType);
}

Type converterType = typeof(EnumConverter<>).MakeGenericType(enumType);
return (JsonConverter)converterType.CreateInstanceNoWrapExceptions(
parameterTypes: [typeof(EnumConverterOptions), typeof(JsonNamingPolicy), typeof(JsonSerializerOptions)],
parameters: [converterOptions, namingPolicy, options])!;
eiriktsarpalis marked this conversation as resolved.
Show resolved Hide resolved
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public JsonNumberEnumConverter() { }
ThrowHelper.ThrowArgumentOutOfRangeException_JsonConverterFactory_TypeNotSupported(typeToConvert);
}

return new EnumConverter<TEnum>(EnumConverterOptions.AllowNumbers, options);
return EnumConverterFactory.Create<TEnum>(EnumConverterOptions.AllowNumbers, options);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public JsonStringEnumConverter(JsonNamingPolicy? namingPolicy = null, bool allow
ThrowHelper.ThrowArgumentOutOfRangeException_JsonConverterFactory_TypeNotSupported(typeToConvert);
}

return new EnumConverter<TEnum>(_converterOptions, _namingPolicy, options);
return EnumConverterFactory.Create<TEnum>(_converterOptions, options, _namingPolicy);
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace System.Text.Json.Serialization
{
/// <summary>
/// Determines the string value that should be used when serializing an enum member.
/// </summary>
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public class JsonStringEnumMemberNameAttribute : Attribute
{
/// <summary>
/// Creates new attribute instance with a specified enum member name.
/// </summary>
/// <param name="name">The name to apply to the current enum member.</param>
public JsonStringEnumMemberNameAttribute(string name)
{
Name = name;
}

/// <summary>
/// Gets the name of the enum member.
/// </summary>
public string Name { get; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@ public static JsonConverter<T> GetEnumConverter<T>(JsonSerializerOptions options
ThrowHelper.ThrowArgumentNullException(nameof(options));
}

return new EnumConverter<T>(EnumConverterOptions.AllowNumbers, options);
return EnumConverterFactory.Create<T>(EnumConverterOptions.AllowNumbers, options);
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -910,9 +910,9 @@ public static void ThrowInvalidOperationException_PolymorphicTypeConfigurationDo
}

[DoesNotReturn]
public static void ThrowInvalidOperationException_InvalidEnumTypeWithSpecialChar(Type enumType, string enumName)
public static void ThrowInvalidOperationException_UnsupportedEnumIdentifier(Type enumType, string? enumName)
{
throw new InvalidOperationException(SR.Format(SR.InvalidEnumTypeWithSpecialChar, enumType.Name, enumName));
throw new InvalidOperationException(SR.Format(SR.UnsupportedEnumIdentifier, enumType.Name, enumName));
}

[DoesNotReturn]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,6 @@ public async Task EnumSerialization_DictionaryPolicy_NotApplied_WhenEnumsAreSeri

Assert.Equal("2", value);


value = await Serializer.SerializeWrapper(new ClassWithEnumProperties(), options);

Assert.Equal("{\"TestEnumProperty1\":2,\"TestEnumProperty2\":1}", value);
Expand All @@ -280,7 +279,7 @@ public async Task EnumSerialization_DictionaryPolicy_ThrowsException_WhenNamingP

InvalidOperationException ex = await Assert.ThrowsAsync<InvalidOperationException>(() => Serializer.SerializeWrapper(dict, options));

Assert.Contains(typeof(CustomJsonNamingPolicy).ToString(), ex.Message);
Assert.Contains("uses unsupported identifier", ex.Message);
}

[Fact]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,10 @@ public static IEnumerable<ITestData> GetTestDataCore()
yield return new TestData<IntEnum>(IntEnum.A, ExpectedJsonSchema: """{"type":"integer"}""");
yield return new TestData<StringEnum>(StringEnum.A, ExpectedJsonSchema: """{"enum":["A","B","C"]}""");
yield return new TestData<FlagsStringEnum>(FlagsStringEnum.A, ExpectedJsonSchema: """{"type":"string"}""");
yield return new TestData<EnumWithNameAttributes>(
EnumWithNameAttributes.Value1,
AdditionalValues: [EnumWithNameAttributes.Value2],
ExpectedJsonSchema: """{"enum":["A","B"]}""");

// Nullable<T> types
yield return new TestData<bool?>(true, AdditionalValues: [null], ExpectedJsonSchema: """{"type":["boolean","null"]}""");
Expand Down Expand Up @@ -1077,6 +1081,15 @@ public enum StringEnum { A, B, C };
[Flags, JsonConverter(typeof(JsonStringEnumConverter<FlagsStringEnum>))]
public enum FlagsStringEnum { A = 1, B = 2, C = 4 };

[JsonConverter(typeof(JsonStringEnumConverter<EnumWithNameAttributes>))]
public enum EnumWithNameAttributes
{
[JsonStringEnumMemberName("A")]
Value1 = 1,
[JsonStringEnumMemberName("B")]
Value2 = 2,
}

public class SimplePoco
{
public string String { get; set; } = "default";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,16 +34,14 @@ optionsDisableNumeric.Converters.Add(new JsonStringEnumConverter(null, false))

[<Fact>]
let ``Deserialize With Exception If Enum Contains Special Char`` () =
let ex = Assert.Throws<TargetInvocationException>(fun () -> JsonSerializer.Deserialize<BadEnum>(badEnumJsonStr, options) |> ignore)
Assert.Equal(typeof<InvalidOperationException>, ex.InnerException.GetType())
Assert.Equal("Enum type 'BadEnum' uses unsupported identifer name 'There's a comma, in my name'.", ex.InnerException.Message)
let ex = Assert.Throws<InvalidOperationException>(fun () -> JsonSerializer.Deserialize<BadEnum>(badEnumJsonStr, options) |> ignore)
eiriktsarpalis marked this conversation as resolved.
Show resolved Hide resolved
Assert.Contains("Enum type 'BadEnum' uses unsupported identifier 'There's a comma, in my name'.", ex.Message)


[<Fact>]
let ``Serialize With Exception If Enum Contains Special Char`` () =
let ex = Assert.Throws<TargetInvocationException>(fun () -> JsonSerializer.Serialize(badEnum, options) |> ignore)
Assert.Equal(typeof<InvalidOperationException>, ex.InnerException.GetType())
Assert.Equal("Enum type 'BadEnum' uses unsupported identifer name 'There's a comma, in my name'.", ex.InnerException.Message)
let ex = Assert.Throws<InvalidOperationException>(fun () -> JsonSerializer.Serialize(badEnum, options) |> ignore)
Assert.Contains("Enum type 'BadEnum' uses unsupported identifier 'There's a comma, in my name'.", ex.Message)

[<Fact>]
let ``Successful Deserialize Normal Enum`` () =
Expand All @@ -52,34 +50,37 @@ let ``Successful Deserialize Normal Enum`` () =

[<Fact>]
let ``Fail Deserialize Good Value Of Bad Enum Type`` () =
let ex = Assert.Throws<TargetInvocationException>(fun () -> JsonSerializer.Deserialize<BadEnum>(badEnumWithGoodValueJsonStr, options) |> ignore)
Assert.Equal(typeof<InvalidOperationException>, ex.InnerException.GetType())
Assert.Equal("Enum type 'BadEnum' uses unsupported identifer name 'There's a comma, in my name'.", ex.InnerException.Message)
let ex = Assert.Throws<InvalidOperationException>(fun () -> JsonSerializer.Deserialize<BadEnum>(badEnumWithGoodValueJsonStr, options) |> ignore)
Assert.Contains("Enum type 'BadEnum' uses unsupported identifier 'There's a comma, in my name'.", ex.Message)

[<Fact>]
let ``Fail Serialize Good Value Of Bad Enum Type`` () =
let ex = Assert.Throws<TargetInvocationException>(fun () -> JsonSerializer.Serialize(badEnumWithGoodValue, options) |> ignore)
Assert.Equal(typeof<InvalidOperationException>, ex.InnerException.GetType())
Assert.Equal("Enum type 'BadEnum' uses unsupported identifer name 'There's a comma, in my name'.", ex.InnerException.Message)
let ex = Assert.Throws<InvalidOperationException>(fun () -> JsonSerializer.Serialize(badEnumWithGoodValue, options) |> ignore)
Assert.Contains("Enum type 'BadEnum' uses unsupported identifier 'There's a comma, in my name'.", ex.Message)

type NumericLabelEnum =
| ``1`` = 1
| ``2`` = 2
| ``3`` = 4

[<Theory>]
[<InlineData("\"1\"")>]
[<InlineData("\"2\"")>]
[<InlineData("\"3\"")>]
[<InlineData("\"4\"")>]
[<InlineData("\"5\"")>]
[<InlineData("\"+1\"")>]
[<InlineData("\"-1\"")>]
[<InlineData("\" 1 \"")>]
[<InlineData("\" +1 \"")>]
[<InlineData("\" -1 \"")>]
let ``Fail Deserialize Numeric label Of Enum When Disallow Integer Values`` (numericValueJsonStr: string) =
Assert.Throws<JsonException>(fun () -> JsonSerializer.Deserialize<NumericLabelEnum>(numericValueJsonStr, optionsDisableNumeric) |> ignore)

[<Theory>]
[<InlineData("\"1\"", NumericLabelEnum.``1``)>]
[<InlineData("\"2\"", NumericLabelEnum.``2``)>]
[<InlineData("\"3\"", NumericLabelEnum.``3``)>]
[<InlineData("\" 1 \"", NumericLabelEnum.``1``)>]
let ``Successful Deserialize Numeric label Of Enum When Disallow Integer Values If Matching Integer Label`` (numericValueJsonStr: string, expectedValue: NumericLabelEnum) =
let actual = JsonSerializer.Deserialize<NumericLabelEnum>(numericValueJsonStr, optionsDisableNumeric)
Assert.Equal(expectedValue, actual)

[<Theory>]
[<InlineData("\"1\"", NumericLabelEnum.``1``)>]
Expand All @@ -88,8 +89,24 @@ let ``Successful Deserialize Numeric label Of Enum When Allowing Integer Values`
let actual = JsonSerializer.Deserialize<NumericLabelEnum>(numericValueJsonStr, options)
Assert.Equal(expectedEnumValue, actual)

[<Theory>]
[<InlineData(-1)>]
[<InlineData(0)>]
[<InlineData(4)>]
[<InlineData(Int32.MaxValue)>]
[<InlineData(Int32.MinValue)>]
let ``Successful Deserialize Numeric label Of Enum But as Underlying value When Allowing Integer Values`` (numericValue: int) =
let actual = JsonSerializer.Deserialize<NumericLabelEnum>($"\"{numericValue}\"", options)
Assert.Equal(LanguagePrimitives.EnumOfValue numericValue, actual)

type CharEnum =
| A = 'A'
| B = 'B'
| C = 'C'

[<Fact>]
let ``Successful Deserialize Numeric label Of Enum But as Underlying value When Allowing Integer Values`` () =
let actual = JsonSerializer.Deserialize<NumericLabelEnum>("\"3\"", options)
Assert.NotEqual(NumericLabelEnum.``3``, actual)
Assert.Equal(LanguagePrimitives.EnumOfValue 3, actual)
let ``Serializing char enums throws NotSupportedException`` () =
Assert.Throws<NotSupportedException>(fun () -> JsonSerializer.Serialize(CharEnum.A) |> ignore) |> ignore
Assert.Throws<NotSupportedException>(fun () -> JsonSerializer.Serialize(CharEnum.A, options) |> ignore) |> ignore
Assert.Throws<NotSupportedException>(fun () -> JsonSerializer.Deserialize<CharEnum>("0") |> ignore) |> ignore
Assert.Throws<NotSupportedException>(fun () -> JsonSerializer.Deserialize<CharEnum>("\"A\"", options) |> ignore) |> ignore
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ public sealed partial class JsonSchemaExporterTests_SourceGen()
[JsonSerializable(typeof(IntEnum))]
[JsonSerializable(typeof(StringEnum))]
[JsonSerializable(typeof(FlagsStringEnum))]
[JsonSerializable(typeof(EnumWithNameAttributes))]
// Nullable<T> types
[JsonSerializable(typeof(bool?))]
[JsonSerializable(typeof(int?))]
Expand Down
Loading
Loading