-
Notifications
You must be signed in to change notification settings - Fork 5.2k
Closed
Labels
api-approvedAPI was approved in API review, it can be implementedAPI was approved in API review, it can be implementedarea-System.Text.Jsonin-prThere is an active PR which will close this issue when it is mergedThere is an active PR which will close this issue when it is merged
Milestone
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.
JuanZamudioGBM, anreton, MarcelJenner, standbych, billhong-just and 78 more
Metadata
Metadata
Assignees
Labels
api-approvedAPI was approved in API review, it can be implementedAPI was approved in API review, it can be implementedarea-System.Text.Jsonin-prThere is an active PR which will close this issue when it is mergedThere is an active PR which will close this issue when it is merged