{"id":67044,"date":"2022-03-15T07:31:27","date_gmt":"2022-03-15T06:31:27","guid":{"rendered":"https:\/\/drafts.code-maze.com\/?p=67044"},"modified":"2022-06-09T09:20:08","modified_gmt":"2022-06-09T07:20:08","slug":"csharp-serialize-enum-to-string","status":"publish","type":"post","link":"https:\/\/code-maze.com\/csharp-serialize-enum-to-string\/","title":{"rendered":"How to Serialize Enum to a String in C#"},"content":{"rendered":"<p>In this article, we are going to learn how to serialize enum to a string in C#.<\/p>\n<div style=\"padding: 20px; border-left: 5px #dc2323 solid; display: block; margin-bottom: 20px; box-shadow: 1px 1px 5px 0px lightgrey;\">To download the source code for this article, you can visit our <a href=\"https:\/\/github.com\/CodeMazeBlog\/CodeMazeGuides\/tree\/main\/json-csharp\/JsonSerializationOfEnumAsString\" target=\"_blank\" rel=\"nofollow noopener\">GitHub repository<\/a>.<\/div>\n<p>In C#, JSON serialization very often needs to deal with <code>enum<\/code> objects. <strong>By default,<\/strong> <code>enums<\/code><strong> are serialized in their integer form. This often causes a lack of interoperability with consumer applications because they need prior knowledge of what those numbers actually mean.<\/strong> So, we want them to serialize as strings in many instances. We are going to see various ways to do this using the native <code>System.Text.Json<\/code> library and\u00a0the popular <code>Newtonsoft.Json<\/code> library. It is a general-purpose solution for most parts.\u00a0<\/p>\n<h2>Default Way to Serialize Enum to String in C#<\/h2>\n<p>To begin, let&#8217;s prepare a few object models:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class Canvas\r\n{\r\n    public static Canvas Poster \r\n        =&gt; new() { Name = \"Poster\", BackColor = Color.LightGray, Pen = new (\"Simple\", Color.Red) };\r\n\r\n    public string? Name { get; set; }\r\n\r\n    public Color BackColor { get; set; }\r\n\r\n    public Medium Medium { get; set; }\r\n\r\n    public Pen? Pen { get; set; }\r\n}\r\n\r\npublic record struct Pen(string Name, Color Color);\r\n\r\npublic enum Color\r\n{\r\n    White, LightGray, DarkGray, Red\r\n}\r\n\r\npublic enum Medium\r\n{\r\n    Water, Oil\r\n}<\/pre>\n<p>We declare two enums: <code>Color<\/code> and <code>Medium<\/code>, a record <code>Pen<\/code>, and a class <code>Canvas<\/code>. <code>Canvas<\/code> is our primary model in concern. Also, we declare a static <code>Canvas<\/code> instance (<code>Poster<\/code>) for convenient use in examples.<\/p>\n<p>Next, we are going to add a basic <code>Serialize<\/code> method in the base class (<code>UnitTestBase<\/code>):<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">\/\/ Native\r\npublic static string Serialize(object obj)\r\n{\r\n    return JsonSerializer.Serialize(obj);\r\n}\r\n\r\n\/\/ Newtonsoft\r\npublic static string Serialize(object obj)\r\n{\r\n    return JsonConvert.SerializeObject(obj);\r\n}<\/pre>\n<p>All set, we&#8217;re ready to go.<\/p>\n<p>First, let&#8217;s check the default behavior of serialization on <code>Canvas.Poster<\/code> object:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var json = Serialize(Canvas.Poster);<\/code><\/p>\n<p>And let&#8217;s inspect the result:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"json\">{\r\n  \"Name\": \"Poster\",\r\n  \"BackColor\": 1,\r\n  \"Medium\": 0,\r\n  \"Pen\": {\r\n    \"Name\": \"Simple\",\r\n    \"Color\": 3\r\n  }\r\n}<\/pre>\n<p>No wonder, the resulting string contains the enum properties (<code>BackColor<\/code>, <code>Medium<\/code>, <code>Pen.Color<\/code>) as integer values.<\/p>\n<p>So, the question arises: &#8220;Can enum be serialized to a string in C#&#8221;? Let&#8217;s look for the answer in the rest of the article.<\/p>\n<h2>Different Ways to Serialize Enum to String in C#<\/h2>\n<p>We want to serialize the enums as strings. Both native and Newtonsoft libraries provide a converter for this purpose, named as <strong>JsonStringEnumConverter<\/strong> and <strong>StringEnumConverter<\/strong> respectively. They also provide an attribute <strong>JsonConverterAttribute<\/strong> that we can use to serialize string-enum selectively.<\/p>\n<h3>Serialization of an Enum Property<\/h3>\n<p>First of all, we want to serialize the <code>BackColor<\/code> property as a string. So, it&#8217;s time to change the <code>Canvas<\/code> model and decorate the <code>BackColor<\/code> property with the converter attribute:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"5,6,14,15\">\/\/ Native\r\npublic class Canvas\r\n{\r\n    ...\r\n    [JsonConverter(typeof(JsonStringEnumConverter))]\r\n    public Color BackColor { get; set; }\r\n    ...\r\n}\r\n\r\n\/\/ Newtonsoft\r\npublic class Canvas\r\n{\r\n    ...\r\n    [JsonConverter(typeof(StringEnumConverter))]\r\n    public Color BackColor { get; set; }\r\n    ...\r\n}<\/pre>\n<p>Now the serialization of <code>Canvas.Poster<\/code> :<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var json = Serialize(Canvas.Poster);<\/code><\/p>\n<p>Produces a different output:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"json\" data-enlighter-highlight=\"3\">{\r\n  \"Name\": \"Poster\",\r\n  \"BackColor\": \"LightGray\",\r\n  \"Medium\": 0,\r\n  \"Pen\": {\r\n    \"Name\": \"Simple\",\r\n    \"Color\": 3\r\n  }\r\n}<\/pre>\n<p>We can see that <code>BackColor<\/code> turns to string but <code>Medium<\/code> and <code>Pen.Color<\/code> don&#8217;t, because they don&#8217;t have the converter attribute applied. This means we can selectively serialize specific <code>enum<\/code> properties in this way.<\/p>\n<h3>Serialization of an Enum Type<\/h3>\n<p>Next, we want to serialize all instances of the <code>Color<\/code> enum to strings. We can do this by applying the converter attribute on the enumeration type itself instead of the properties:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"4,9-10,16-17\">public class Canvas\r\n{\r\n    ...\r\n    public Color BackColor { get; set; }\r\n    ...\r\n}\r\n\r\n\/\/ Native\r\n[JsonConverter(typeof(JsonStringEnumConverter))]\r\npublic enum Color\r\n{\r\n    White,\u00a0LightGray,\u00a0DarkGray,\u00a0Red\r\n}\r\n\r\n\/\/ Newtonsoft\r\n[JsonConverter(typeof(StringEnumConverter))]\r\npublic enum Color\r\n{\r\n    White, LightGray, DarkGray, Red\r\n}<\/pre>\n<p>Again, after the serialization, the end result differs from the previous one:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"json\" data-enlighter-highlight=\"3,7\">{\r\n  \"Name\": \"Poster\",\r\n  \"BackColor\": \"LightGray\",\r\n  \"Medium\": 0,\r\n  \"Pen\": {\r\n    \"Name\": \"Simple\",\r\n    \"Color\": \"Red\"\r\n  }\r\n}<\/pre>\n<p>This time we can see all <code>Color<\/code> instances (<code>BackColor<\/code> and <code>Pen.Color<\/code>) turn to string, but <code>Medium<\/code> enum still follows the default behavior. So in this way, we can selectively serialize some specific enum types to string.<\/p>\n<h2>Inline JSON Serialization of Enum to String<\/h2>\n<p>We can&#8217;t go with the attribute-based approaches in some cases such as:<\/p>\n<ul>\n<li>Dealing with system types or third party library models<\/li>\n<li>Serialize objects generated on the fly e.g. anonymous objects<\/li>\n<li>Don&#8217;t want to pollute our domain models but still want to get enum as a string<\/li>\n<li>Stringify enums only for a particular object instance, not all instances in general<\/li>\n<\/ul>\n<p>In such cases, if we don&#8217;t bother about selective serialization, we can instruct the serializer to convert enum on-demand. Both libraries offer an overload to pass converters in line with the serialization method. So, let&#8217;s implement our second serialization routine in the base class:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">\/\/ Native\r\npublic static string SerializeWithStringEnum(object obj)\r\n{\r\n    var options = new JsonSerializerOptions();\r\n    options.Converters.Add(new JsonStringEnumConverter());\r\n\r\n    return JsonSerializer.Serialize(obj, options);\r\n}\r\n\r\n\/\/ Newtonsoft\r\npublic static string SerializeWithStringEnum(object obj)\r\n{\r\n    var converter = new StringEnumConverter();\r\n    return JsonConvert.SerializeObject(obj, converter);\r\n}<\/pre>\n<p>In the case of the native version, we instantiate a <code>JsonSerializerOptions<\/code> class. Then we register the enum converter there and finally call the appropriate <code>Serialize<\/code> method.\u00a0<\/p>\n<p>Things are a bit straightforward for Newtonsoft. We can directly pass the converter to the serializing method.<\/p>\n<p>Next, <strong>we are going to get rid of the converter attributes from all our models<\/strong> and instead apply this new method on <code>Canvas.Poster<\/code> and an anonymous object:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var poster = SerializeWithStringEnum(Canvas.Poster);\r\nvar schedule = SerializeWithStringEnum(new { Description = \"Exhibition\", Day = DayOfWeek.Monday });<\/pre>\n<p>Now, we can inspect the result:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"json\" data-enlighter-highlight=\"4,5,8,14\">\/* poster *\/\r\n{\r\n  \"Name\": \"Poster\",\r\n  \"BackColor\": \"LightGray\",\r\n  \"Medium\": \"Water\",\r\n  \"Pen\": {\r\n    \"Name\": \"Simple\",\r\n    \"Color\": \"Red\"\r\n  }\r\n}\r\n\/* schedule *\/\r\n{\r\n  \"Description\": \"Exhibition\",\r\n  \"Day\": \"Monday\"\r\n}<\/pre>\n<p>As we expect, all enums of the target objects are serialized in a string form.<\/p>\n<h2>Global JSON Serialization of Enum to String<\/h2>\n<p>Attribute-based ways give us the flexibility to manipulate the enum serialization in a controlled way. And the options-based way allows us to deal with specific object instances on demand. <strong>But, is there any way to make all enums serialized as strings by default?<\/strong> Yes, there is!\u00a0<\/p>\n<p>To make the string-enum converter default choice for enum serialization, we need some bootstrapping that varies depending on the application types. Typically this means, we have to register the enum converter in the DI pipeline. Here, we will focus on ASP.NET Core applications mainly.<\/p>\n<h3>Configure ASP.NET Core Web API<\/h3>\n<p>We are going to start with a basic ASP.NET Core Web API project and remove all auto-generated controllers and models. Next, let&#8217;s add our object models as usual and a <code>CanvasController<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">[ApiController]\r\n[Route(\"[controller]\")]\r\npublic class CanvasController : ControllerBase\r\n{\r\n    [HttpGet(\"poster\")]\r\n    public Canvas GetPoster() =&gt; Canvas.Poster;\r\n\r\n    [HttpGet(\"schedule\")]\r\n    public object GetSchedule() =&gt; new { Description = \"Exhibition\", Day = DayOfWeek.Monday };\r\n}<\/pre>\n<p>This is a typical Web API controller with two simple endpoints: &#8220;canvas\/poster&#8221; and &#8220;canvas\/schedule&#8221;. They provide output for <code>Canvas.Poster<\/code> and an anonymous object respectively.<\/p>\n<p>Now, let&#8217;s move to the entry point, the <code>Program<\/code> class:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"5-8\">\/\/ Native\r\nvar builder = WebApplication.CreateBuilder(args);\r\n\r\nbuilder.Services.AddControllers()\r\n    .AddJsonOptions(options =&gt;\r\n    {\r\n        options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());\r\n    });\r\n\r\nvar app = builder.Build();\r\n\r\napp.UseAuthorization();\r\n\r\napp.MapControllers();\r\n\r\napp.Run();<\/pre>\n<p>The highlighted part is all that we need to change in this boilerplate code. We just get into the DI pipeline using the <code>AddJsonOptions<\/code> method and get access to the <code>JsonSerializerOptions<\/code> configuration. This is where we can register the native string-enum converter. That&#8217;s all! Every time the framework attempts to serialize enum to JSON, it will pick this converter from the DI pipeline.<\/p>\n<p>We can do this for Newtonsoft in a similar fashion:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"4-7\">...\r\nbuilder.Services.AddControllers()\r\n    .AddNewtonsoftJson(options =&gt;\r\n    {\r\n        options.SerializerSettings.Converters.Add(new StringEnumConverter());\r\n    });\r\n...<\/pre>\n<p>Again, all we need is to find the appropriate DI configurator method to use the Newtonsoft serializer. For this, we have to install <code>Microsoft.AspNetCore.Mvc.NewtonsoftJson<\/code> package. This provides the\u00a0<code>AddNewtonsoftJson<\/code> configurator method. It exposes the serializer settings where we can register the Newtonsoft enum converter.<\/p>\n<p>Now, we can examine the output of our API endpoints from Postman or directly from a browser:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"json\" data-enlighter-highlight=\"4,5,8,14\">\/* http:\/\/localhost:5045\/canvas\/poster *\/\r\n{\r\n  \"name\": \"Poster\",\r\n  \"backColor\": \"LightGray\",\r\n  \"medium\": \"Water\",\r\n  \"pen\": {\r\n    \"name\": \"Simple\",\r\n    \"color\": \"Red\"\r\n  }\r\n}\r\n\/* http:\/\/localhost:5045\/canvas\/schedule *\/\r\n{\r\n  \"description\": \"Exhibition\",\r\n  \"day\": \"Monday\"\r\n}<\/pre>\n<p>We get exactly what we desire, all string-enums by default!<\/p>\n<h3>Configure ASP.NET Core Minimal API<\/h3>\n<p>Next, we are going to explore the configuration for the cutting-edge .NET technology: <a href=\"https:\/\/code-maze.com\/dotnet-minimal-api\/\" target=\"_blank\" rel=\"noopener\">Minimal API<\/a>. This is Web API at its core, but the bootstrapping steps are a bit different. <strong>Also, Minimal API does not yet support configuring Newtonsoft out of the box<\/strong>. So, we are going to discuss only <code>System.Text.Json<\/code> library.<\/p>\n<p>Let&#8217;s modify our auto-generated <code>Program<\/code> class and add the bootstrapping code:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"2-5, 9-10\">var builder = WebApplication.CreateBuilder(args);\r\nbuilder.Services.Configure&lt;JsonOptions&gt;(options =&gt;\r\n{\r\n    options.SerializerOptions.Converters.Add(new JsonStringEnumConverter());\r\n});\r\n\r\nvar app = builder.Build();\r\n\r\napp.MapGet(\"\/poster\", () =&gt; Canvas.Poster);\r\napp.MapGet(\"\/schedule\", () =&gt; new { Description = \"Exhibition\", Day = DayOfWeek.Monday });\r\n\r\napp.Run();<\/pre>\n<p>This time, we configure the <code>JsonOptions<\/code> to register the string-enum converter. In addition, we map two routes: <strong>poster<\/strong> and <strong>schedule<\/strong>. These endpoints work the same as our previous controller examples and the output is also identical.<\/p>\n<p>As we can see, we can set up our application for serializing enums as strings by default without any extra model decoration! In this way, we can work with clean models. Also, we don&#8217;t need to worry about specifying explicit options every time we serialize an object.\u00a0<\/p>\n<h2>Serialization of Enum to a Customized String<\/h2>\n<p>While serializing enum to a string, we may want some fine-tuning. For example, transform to camelCase or expose as a more meaningful text, etc. Let&#8217;s explore how we can do these.<\/p>\n<h3>Serialize to a camelCase Text<\/h3>\n<p>JSON serialization to a camelCase string is a common practice. This is in fact the default behavior for ASP.NET Core. But in general, this means camelCase transformation of property names, not their values:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">\/\/ Native\r\nvar options = new JsonSerializerOptions\r\n{\r\n    PropertyNamingPolicy = JsonNamingPolicy.CamelCase\r\n};\r\noptions.Converters.Add(new JsonStringEnumConverter());\r\n\r\nvar json = JsonSerializer.Serialize(Canvas.Poster, options);<\/pre>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"json\">{\r\n  \"name\": \"Poster\",\r\n  \"backColor\": \"LightGray\",\r\n  \"medium\": \"Water\",\r\n  \"pen\": {\r\n    \"name\": \"Simple\",\r\n    \"color\": \"Red\"\r\n  }\r\n}<\/pre>\n<p>This is self-explanatory and technically logical but may not be desirable for enums in practice. That&#8217;s why the enum converter offers a way to explicitly transform enum values to camelCase:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">\/\/ Native\r\nvar options = new JsonSerializerOptions();\r\noptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase));\r\n\r\nvar json = JsonSerializer.Serialize(Canvas.Poster, options);\r\n\r\n\/\/ Newtonsoft\r\nvar converter = new StringEnumConverter(new CamelCaseNamingStrategy());\r\nvar json = JsonConvert.SerializeObject(Canvas.Poster, converter);\r\n<\/pre>\n<p>We just need to specify the camelCase policy (or strategy) during the enum converter instantiation and pass it during serialization as usual:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"json\" data-enlighter-highlight=\"3,4,7\">{\r\n  \"Name\": \"Poster\",\r\n  \"BackColor\": \"lightGray\",\r\n  \"Medium\": \"water\",\r\n  \"Pen\": {\r\n    \"Name\": \"Simple\",\r\n    \"Color\": \"red\"\r\n  }\r\n}<\/pre>\n<p>All the enum values are now in camelCase format.<\/p>\n<h3>Serialize as Custom Text<\/h3>\n<p>Because of language&#8217;s variable naming rules, an enum member can&#8217;t always convey meaningful text when serialized in a regular way. To get around this problem, we generally use <code>EnumMemberAttribute<\/code> from <code>System.Runtime.Serialization<\/code> assembly that is specifically introduced for this purpose:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public record struct ToggleControl(string Name, ToggleType Type);\r\n\r\npublic enum ToggleType\r\n{\r\n    [EnumMember(Value = \"Enable\/Disable\")]\r\n    EnableDisable,\r\n\r\n    [EnumMember(Value = \"Visible\/Hidden\")]\r\n    VisibleHidden,\r\n\r\n    [EnumMember(Value = \"Editable\/Readonly\")]\r\n    EditableReadonly,\r\n}<\/pre>\n<p>We define a <code>ToggleType<\/code> enum that has <code>EnumMemberAttribute<\/code> on its members to provide more meaningful values than their names. We also define a <code>ToggleControl<\/code> record that uses this enum.<\/p>\n<p>That&#8217;s it, we&#8217;re ready to go.<\/p>\n<p><strong>Sadly, the native library doesn&#8217;t support EnumMemberAttribute yet, but Newtonsoft does.<\/strong> We can implement a custom converter extending from the native <code>JsonStringEnumConverter<\/code> and add this functionality on our own. But, that is another level of job that we will try to cover in a future post. For now, let&#8217;s just stick with Newtonsoft:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">\/\/ Newtonsoft\r\nvar controls = new ToggleControl[]\r\n{ \r\n    new(\"toggle1\", ToggleType.EnableDisable),\r\n    new(\"toggle2\", ToggleType.VisibleHidden)\r\n};\r\nvar json = SerializeWithStringEnum(controls);<\/pre>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"json\">[\r\n  {\r\n    \"Name\": \"toggle1\",\r\n    \"Type\": \"Enable\/Disable\"\r\n  },\r\n  {\r\n    \"Name\": \"toggle2\",\r\n    \"Type\": \"Visible\/Hidden\"\r\n  }\r\n]<\/pre>\n<p>We create an array of <code>ToggleControl<\/code> with different <code>ToggleType<\/code> values. On serialization, we can see it produces output with our desired texts!<\/p>\n<h2>JSON Serialization of Flag enums<\/h2>\n<p>Default serialization of flag enums (bit-mask enum) produces even more odd output. Instead of representing as a combination of flags, they&#8217;re exposed as a combined value:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">[Flags]\r\npublic enum TextStyles\r\n{\r\n    None = 0,\r\n    Bold = 1,\r\n    Italic = 2,\r\n    Underline = 4,\r\n}\r\n\r\nvar styles = TextStyles.Bold | TextStyles.Italic | TextStyles.Underline;\r\nvar json = Serialize(new { Format = styles });\r\n<\/pre>\n<p>The output:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"json\">{\"Format\":7}<\/code><\/p>\n<p>We start with defining a <code>TextStyles<\/code> flag. Then we declare a <code>styles<\/code> which is a combination of <code>Bold(1)<\/code>, <code>Italic(2)<\/code>, <code>Underline(4)<\/code> flags. For default serialization, we may expect it to serialize as &#8220;1, 2, 4&#8221; at least. But, we get a <strong>7<\/strong> instead because the default serializer just cares about the numeric value for enum.<\/p>\n<p>The string-enum conversion is free from this oddness:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"2\">var styles = TextStyles.Bold | TextStyles.Italic | TextStyles.Underline;\r\nvar json = SerializeWithStringEnum(new { Format = styles });<\/pre>\n<p>Now we have a different result:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"json\">{\"Format\":\"Bold, Italic, Underline\"}<\/code><\/p>\n<p>That&#8217;s the output we desire!<\/p>\n<h2>Conclusion<\/h2>\n<p>In this article, we have learned a few ways of JSON serialization of enum as a string. We have also discussed various techniques to get customized string serialization of an enum.<\/p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we are going to learn how to serialize enum to a string in C#. In C#, JSON serialization very often needs to deal with enum objects. By default, enums are serialized in their integer form. This often causes a lack of interoperability with consumer applications because they need prior knowledge of what [&hellip;]<\/p>\n","protected":false},"author":38,"featured_media":62189,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_et_pb_use_builder":"","_et_pb_old_content":"","_et_gb_content_width":"","footnotes":""},"categories":[12,506],"tags":[1143,927,1147,1145,928,1144,1146],"class_list":["post-67044","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-csharp","category-intermediate","tag-enum","tag-json","tag-jsonconverterattribute","tag-jsonstringenumconverter","tag-serialization","tag-serialize-enum-to-a-string","tag-stringenumconverter","et-has-post-format-content","et_post_format-et-post-format-standard"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>How to Serialize Enum to a String in C# - Code Maze<\/title>\n<meta name=\"description\" content=\"In this article, we will demonstrate different ways of how to serialize enum to string in C# with detailed explanation and examples\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/code-maze.com\/csharp-serialize-enum-to-string\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"How to Serialize Enum to a String in C# - Code Maze\" \/>\n<meta property=\"og:description\" content=\"In this article, we will demonstrate different ways of how to serialize enum to string in C# with detailed explanation and examples\" \/>\n<meta property=\"og:url\" content=\"https:\/\/code-maze.com\/csharp-serialize-enum-to-string\/\" \/>\n<meta property=\"og:site_name\" content=\"Code Maze\" \/>\n<meta property=\"article:published_time\" content=\"2022-03-15T06:31:27+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2022-06-09T07:20:08+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1100\" \/>\n\t<meta property=\"og:image:height\" content=\"620\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Ahsan Ullah\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@CodeMazeBlog\" \/>\n<meta name=\"twitter:site\" content=\"@CodeMazeBlog\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Ahsan Ullah\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"10 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":[\"Article\",\"BlogPosting\"],\"@id\":\"https:\/\/code-maze.com\/csharp-serialize-enum-to-string\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/csharp-serialize-enum-to-string\/\"},\"author\":{\"name\":\"Ahsan Ullah\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/90ad30bf08ba4a2ee4d4489a005da7e0\"},\"headline\":\"How to Serialize Enum to a String in C#\",\"datePublished\":\"2022-03-15T06:31:27+00:00\",\"dateModified\":\"2022-06-09T07:20:08+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/code-maze.com\/csharp-serialize-enum-to-string\/\"},\"wordCount\":1527,\"commentCount\":13,\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/csharp-serialize-enum-to-string\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"keywords\":[\"enum\",\"JSON\",\"JsonConverterAttribute\",\"JsonStringEnumConverter\",\"Serialization\",\"Serialize Enum to a String\",\"StringEnumConverter\"],\"articleSection\":[\"C#\",\"Intermediate\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/code-maze.com\/csharp-serialize-enum-to-string\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/code-maze.com\/csharp-serialize-enum-to-string\/\",\"url\":\"https:\/\/code-maze.com\/csharp-serialize-enum-to-string\/\",\"name\":\"How to Serialize Enum to a String in C# - Code Maze\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/code-maze.com\/csharp-serialize-enum-to-string\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/csharp-serialize-enum-to-string\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"datePublished\":\"2022-03-15T06:31:27+00:00\",\"dateModified\":\"2022-06-09T07:20:08+00:00\",\"description\":\"In this article, we will demonstrate different ways of how to serialize enum to string in C# with detailed explanation and examples\",\"breadcrumb\":{\"@id\":\"https:\/\/code-maze.com\/csharp-serialize-enum-to-string\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/code-maze.com\/csharp-serialize-enum-to-string\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/csharp-serialize-enum-to-string\/#primaryimage\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"width\":1100,\"height\":620,\"caption\":\"C# Development\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/code-maze.com\/csharp-serialize-enum-to-string\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/code-maze.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"How to Serialize Enum to a String in C#\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/code-maze.com\/#website\",\"url\":\"https:\/\/code-maze.com\/\",\"name\":\"Code Maze\",\"description\":\"Learn. Code. Succeed.\",\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/code-maze.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/code-maze.com\/#organization\",\"name\":\"Code Maze\",\"url\":\"https:\/\/code-maze.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"width\":3511,\"height\":3510,\"caption\":\"Code Maze\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/CodeMazeBlog\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/90ad30bf08ba4a2ee4d4489a005da7e0\",\"name\":\"Ahsan Ullah\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/12\/ahsan-ullah-profile-150x150.jpeg\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/12\/ahsan-ullah-profile-150x150.jpeg\",\"caption\":\"Ahsan Ullah\"},\"description\":\"A Senior IT Developer with demonstrated proficiency (10+ years of experience) in supply chain management software projects of DSV A\/S. Senior member of the core development team helping to meet growing business demands. Competent in the .NET platform and Angular applications. Other expertise includes skills in database development, designing algorithms, and developing interfaces from low-level responsive html tools to high-level middleware services.\",\"sameAs\":[\"https:\/\/www.linkedin.com\/in\/md-ahsan-ullah-665aa7215\/\"],\"url\":\"https:\/\/code-maze.com\/author\/aullah\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"How to Serialize Enum to a String in C# - Code Maze","description":"In this article, we will demonstrate different ways of how to serialize enum to string in C# with detailed explanation and examples","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/code-maze.com\/csharp-serialize-enum-to-string\/","og_locale":"en_US","og_type":"article","og_title":"How to Serialize Enum to a String in C# - Code Maze","og_description":"In this article, we will demonstrate different ways of how to serialize enum to string in C# with detailed explanation and examples","og_url":"https:\/\/code-maze.com\/csharp-serialize-enum-to-string\/","og_site_name":"Code Maze","article_published_time":"2022-03-15T06:31:27+00:00","article_modified_time":"2022-06-09T07:20:08+00:00","og_image":[{"width":1100,"height":620,"url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","type":"image\/png"}],"author":"Ahsan Ullah","twitter_card":"summary_large_image","twitter_creator":"@CodeMazeBlog","twitter_site":"@CodeMazeBlog","twitter_misc":{"Written by":"Ahsan Ullah","Est. reading time":"10 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":["Article","BlogPosting"],"@id":"https:\/\/code-maze.com\/csharp-serialize-enum-to-string\/#article","isPartOf":{"@id":"https:\/\/code-maze.com\/csharp-serialize-enum-to-string\/"},"author":{"name":"Ahsan Ullah","@id":"https:\/\/code-maze.com\/#\/schema\/person\/90ad30bf08ba4a2ee4d4489a005da7e0"},"headline":"How to Serialize Enum to a String in C#","datePublished":"2022-03-15T06:31:27+00:00","dateModified":"2022-06-09T07:20:08+00:00","mainEntityOfPage":{"@id":"https:\/\/code-maze.com\/csharp-serialize-enum-to-string\/"},"wordCount":1527,"commentCount":13,"publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"image":{"@id":"https:\/\/code-maze.com\/csharp-serialize-enum-to-string\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","keywords":["enum","JSON","JsonConverterAttribute","JsonStringEnumConverter","Serialization","Serialize Enum to a String","StringEnumConverter"],"articleSection":["C#","Intermediate"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/code-maze.com\/csharp-serialize-enum-to-string\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/code-maze.com\/csharp-serialize-enum-to-string\/","url":"https:\/\/code-maze.com\/csharp-serialize-enum-to-string\/","name":"How to Serialize Enum to a String in C# - Code Maze","isPartOf":{"@id":"https:\/\/code-maze.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/code-maze.com\/csharp-serialize-enum-to-string\/#primaryimage"},"image":{"@id":"https:\/\/code-maze.com\/csharp-serialize-enum-to-string\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","datePublished":"2022-03-15T06:31:27+00:00","dateModified":"2022-06-09T07:20:08+00:00","description":"In this article, we will demonstrate different ways of how to serialize enum to string in C# with detailed explanation and examples","breadcrumb":{"@id":"https:\/\/code-maze.com\/csharp-serialize-enum-to-string\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/code-maze.com\/csharp-serialize-enum-to-string\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/csharp-serialize-enum-to-string\/#primaryimage","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","width":1100,"height":620,"caption":"C# Development"},{"@type":"BreadcrumbList","@id":"https:\/\/code-maze.com\/csharp-serialize-enum-to-string\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/code-maze.com\/"},{"@type":"ListItem","position":2,"name":"How to Serialize Enum to a String in C#"}]},{"@type":"WebSite","@id":"https:\/\/code-maze.com\/#website","url":"https:\/\/code-maze.com\/","name":"Code Maze","description":"Learn. Code. Succeed.","publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/code-maze.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/code-maze.com\/#organization","name":"Code Maze","url":"https:\/\/code-maze.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","width":3511,"height":3510,"caption":"Code Maze"},"image":{"@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/CodeMazeBlog"]},{"@type":"Person","@id":"https:\/\/code-maze.com\/#\/schema\/person\/90ad30bf08ba4a2ee4d4489a005da7e0","name":"Ahsan Ullah","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/person\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/12\/ahsan-ullah-profile-150x150.jpeg","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2023\/12\/ahsan-ullah-profile-150x150.jpeg","caption":"Ahsan Ullah"},"description":"A Senior IT Developer with demonstrated proficiency (10+ years of experience) in supply chain management software projects of DSV A\/S. Senior member of the core development team helping to meet growing business demands. Competent in the .NET platform and Angular applications. Other expertise includes skills in database development, designing algorithms, and developing interfaces from low-level responsive html tools to high-level middleware services.","sameAs":["https:\/\/www.linkedin.com\/in\/md-ahsan-ullah-665aa7215\/"],"url":"https:\/\/code-maze.com\/author\/aullah\/"}]}},"_links":{"self":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/67044","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/users\/38"}],"replies":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/comments?post=67044"}],"version-history":[{"count":5,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/67044\/revisions"}],"predecessor-version":[{"id":67543,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/67044\/revisions\/67543"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media\/62189"}],"wp:attachment":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media?parent=67044"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/categories?post=67044"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/tags?post=67044"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}