Skip to content

Commit

Permalink
Support for overriding enum field name in JsonConverterEnum -- Fix in…
Browse files Browse the repository at this point in the history
…correct attribute usage. Fix build issues on some platforms. (dotnet#31081)
  • Loading branch information
jmaine committed May 27, 2020
1 parent 2c6acd0 commit f1a83cd
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/libraries/System.Text.Json/ref/System.Text.Json.cs
Original file line number Diff line number Diff line change
Expand Up @@ -535,7 +535,7 @@ public JsonStringEnumConverter(System.Text.Json.JsonNamingPolicy? namingPolicy =
public override bool CanConvert(System.Type typeToConvert) { throw null; }
public override System.Text.Json.Serialization.JsonConverter CreateConverter(System.Type typeToConvert, System.Text.Json.JsonSerializerOptions options) { throw null; }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Property, AllowMultiple=false)]
[System.AttributeUsageAttribute(System.AttributeTargets.Field, AllowMultiple=false)]
public sealed partial class JsonStringEnumMemberAttribute : System.Text.Json.Serialization.JsonAttribute
{
public JsonStringEnumMemberAttribute(string name) { }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,14 +50,15 @@ public EnumConverter(EnumConverterOptions options, JsonNamingPolicy? namingPolic
_namingPolicy = namingPolicy;

if (_converterOptions.HasFlag(EnumConverterOptions.AllowStrings)) {
var fields = typeof(T).GetFields();
var enumType = typeof(T);
var fields = enumType.GetFields();
foreach (var field in fields) {
var attribute = field.GetCustomAttribute<JsonStringEnumMemberAttribute>(false);

if (attribute != null) {
_enumToStringCache ??= new ConcurrentDictionary<T, string>();
_stringToEnumCache ??= new ConcurrentDictionary<ValueTuple<string?>, T>();
var enumValue = Enum.Parse<T>(field.Name);
var enumValue = (T) Enum.Parse(enumType, field.Name);
_enumToStringCache[enumValue] = attribute.Name;
_stringToEnumCache[ValueTuple.Create(attribute.Name)] = enumValue;
}
Expand Down

0 comments on commit f1a83cd

Please sign in to comment.