Serializing Enums as Strings in C# JSON
When working with JSON in C#, you might encounter a scenario where you want to serialize an enum as a string instead of its underlying value. This can be particularly useful when you want your JSON to be human-readable or when you're working with an API that expects enum values as strings. In this article, we'll explore how to achieve this using the `JsonSerializer` class and custom JSON converters.
Understanding the Default Behavior
By default, when you serialize an enum in C#, it's converted to its underlying value. For example, consider the following enum:
public enum Color
{
Red,
Green,
Blue
}
If you serialize an instance of this enum, you'll get the underlying value:

var color = Color.Red;
string json = JsonSerializer.Serialize(color); // Output: "0"
Using the JsonStringEnumConverter
The `JsonStringEnumConverter` class is a built-in JSON converter provided by the `System.Text.Json` library that can serialize enums as strings. To use it, you need to apply it to your enum using the `[JsonConverter]` attribute:
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum Color
{
Red,
Green,
Blue
}
Now, when you serialize an instance of this enum, you'll get the string representation:
var color = Color.Red;
string json = JsonSerializer.Serialize(color); // Output: "Red"
Custom JSON Converters
While `JsonStringEnumConverter` works well for most cases, you might need to create a custom JSON converter when you have specific requirements. For instance, you might want to use a different string representation for your enum values. Here's how you can create a custom JSON converter:

Creating the Custom Converter
First, create a class that implements the `JsonConverter` interface:
public class CustomEnumConverter : JsonConverter<Color>
{
public override Color Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
// Implement deserialization logic here
throw new NotImplementedException();
}
public override void Write(Utf8JsonWriter writer, Color value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToString());
}
}
Applying the Custom Converter
Next, apply the custom converter to your enum using the `[JsonConverter]` attribute. You can either apply it to the enum itself or to the specific property that uses the enum:
[JsonConverter(typeof(CustomEnumConverter))]
public enum Color
{
Red,
Green,
Blue
}
or

public class MyClass
{
[JsonConverter(typeof(CustomEnumConverter))]
public Color FavoriteColor { get; set; }
}
Conclusion
In this article, we've explored how to serialize enums as strings in C# JSON using the `JsonStringEnumConverter` and custom JSON converters. By applying these techniques, you can control how your enums are serialized, making your JSON more human-readable and easier to work with. Happy coding!






















