Search code examples
c#.net.net-core.net-core-3.0system.text.json

System.Text.Json: How do I specify a custom name for an enum value?


Using the System.Text.Json serializer capabilities in .NET Core, how can I specify a custom value for an enum value, similar to JsonPropertyName? For example:

public enum Example {
  Trick, 
  Treat, 
  [JsonPropertyName("Trick-Or-Treat")] // Error: Attribute 'JsonPropertyName' is not valid on this declaration type. It is only valid on 'property, indexer' declarations.
   TrickOrTreat
}

Solution

  • This is finally supported from .NET 9 with JsonStringEnumMemberNameAttribute!