Serialize and deserialize enum values to custom string in C# with Json.NET
The code used for this blog post is located in dotnet.core.templates GitHub repository.
Use case description
Enums provide an efficient way to define a set of named integral constants that may be assigned to a variable. They are strongly typed values and are preferred choice over the string constants. In the given example there is an API that provides functionality to save or get movies with title and genre. Although not the best example, as the genre can have lots of values, but it still can be presented as an enum. In the same setup, there is a user interface that consumes the get API. In the UI it is more convenient to directly display the genre as text, so control over naming convention happens in the backend and there is no mapping in the frontend, and localization is ignored in the current example.Serialize and deserialize
Serialization and deserialization to a custom string can be done with two steps. The first is to add an attribute to all enum values which gives the preferred string mapping.using System.Runtime.Serialization;
public enum MovieGenre
{
[EnumMember(Value = "Action Movie")]
Action,
[EnumMember(Value = "Drama Movie")]
Drama
}
Then Json.NET is instructed to serialize/deserialize the enum value as a string with [JsonConverter(typeof(StringEnumConverter))] attribute.
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public class Movie
{
public string Title { get; set; }
[JsonConverter(typeof(StringEnumConverter))]
public MovieGenre Genre { get; set; }
}
This results in the following JSON:
{
"Title": "Die Hard",
"Genre": "Action Movie"
}
In the example above, if [EnumMember(Value = “Action Movie”)] is not provided in the enum declaration, then the string representation of the enum value is taken:
{
"Title": "Die Hard",
"Genre": "Action"
}