"C# JSON Serializer: Enum as String"

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:

N Murderdrones Icons, N From Glitch Pfp, Computer Animation, Pfp Designation, Absolute Solver Symbol Md, Serial Designation N Pilot Hat, Serial Designation N Pfp, Md Drones, Serial Destination N Pfp
N Murderdrones Icons, N From Glitch Pfp, Computer Animation, Pfp Designation, Absolute Solver Symbol Md, Serial Designation N Pilot Hat, Serial Designation N Pfp, Md Drones, Serial Destination N Pfp

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:

a drawing of a woman with a hair dryer in her hand
a drawing of a woman with a hair dryer in her hand

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

an anime character with white hair and black clothes, holding a glass in his hand
an anime character with white hair and black clothes, holding a glass in his hand

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!

KINGER
KINGER
meryemin
meryemin
окак
окак
13K views · 50 reactions | ⚡ Know Your Cables & Speeds! 🔹 USB 3.0 – 5 Gbps 🔹 USB-C – 40 Gbps 🔹 HDMI – 48 Gbps (4K/8K) 🔹 USB-A – 5 Gbps 🔹 Micro USB – 480 Mbps 🔹 S/PDIF / TRS / RCA – Audio only 💡 Faster cables = better performance #TechTips #USB #HDMI #DataSpeed | BD Tech Tips 2.0 | Facebook
13K views · 50 reactions | ⚡ Know Your Cables & Speeds! 🔹 USB 3.0 – 5 Gbps 🔹 USB-C – 40 Gbps 🔹 HDMI – 48 Gbps (4K/8K) 🔹 USB-A – 5 Gbps 🔹 Micro USB – 480 Mbps 🔹 S/PDIF / TRS / RCA – Audio only 💡 Faster cables = better performance #TechTips #USB #HDMI #DataSpeed | BD Tech Tips 2.0 | Facebook
whisper
whisper
the wiring diagram for an internet cable in a notebook
the wiring diagram for an internet cable in a notebook
Transmitter Receiver Circuit for 80-meter Ham Radio – Homemade Circuit Projects
Transmitter Receiver Circuit for 80-meter Ham Radio – Homemade Circuit Projects
nhad sav me.....nhad...
nhad sav me.....nhad...
jester and jack
jester and jack
Cool tree monster
Cool tree monster
an open envelope and some string tied to it sitting on top of a pile of mail
an open envelope and some string tied to it sitting on top of a pile of mail
tying you to me
tying you to me
sisi stringer
sisi stringer
Slim Jim and J Pole calculator – M0UKD – Amateur Radio Blog
Slim Jim and J Pole calculator – M0UKD – Amateur Radio Blog
Atom- Komplex
Atom- Komplex
the three resists are connected in a circuit as shown on the diagram above it
the three resists are connected in a circuit as shown on the diagram above it
kinger👍
kinger👍
an electronic circuit diagram showing the components and instructions for each device, including two different types of
an electronic circuit diagram showing the components and instructions for each device, including two different types of
an electronic circuit diagram with the words video transmitter
an electronic circuit diagram with the words video transmitter
an electrical wiring diagram for a three phase generator
an electrical wiring diagram for a three phase generator
Guys I hope I don’t fail my passion project🥹
Guys I hope I don’t fail my passion project🥹
an electronic circuit diagram with multiple components
an electronic circuit diagram with multiple components
🌟Zen🌟  and ⚡Scrap⚡
🌟Zen🌟 and ⚡Scrap⚡