Closed
Description
API Proposal
Concerning the question of adding built-in enum name customization support, this would need to be done via a new attribute type:
namespace System.Text.Json.Serialization;
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public class JsonStringEnumMemberNameAttribute : Attribute
{
public JsonStringEnumMemberNameAttribute(string name);
public string Name { get; }
}
API Usage
Setting the attribute on individual enum members can customize their name
JsonSerializer.Serialize(MyEnum.Value1 | MyEnum.Value2); // "A, B"
[Flags, JsonConverter(typeof(JsonStringEnumConverter))]
public enum MyEnum
{
[JsonStringEnumMemberName("A")]
Value1 = 1,
[JsonStringEnumMemberName("B")]
Value2 = 2,
}
Original Post
[Issue 31081](https://github.com//issues/31081) was closed in favor of [issue 29975](https://github.com//issues/29975), however the scope of the issues differ.Issues 29975 is a discussion regarding the DataContract
and DataMember
attributes in general. Although JsonStringEnumConverter
does address the straight conversion between an enum and its direct string representation, it does not in fact address cases where the string is not a direct match to the enum value.
The following enum will NOT convert properly using the current implementation of JsonStringEnumConverter
:
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum GroupType
{
[EnumMember(Value = "A")]
Administrator,
[EnumMember(Value = "U")]
User
}
Suggested Workaround
See this gist for a recommended workaround that works for both AOT and reflection-based scenaria.