Tuesday Coding Tip 28 — (de)serializing JSON string enum in C#

●5 ●27 ●93
calendar_today • schedule1 min read
— Originally published at medium.com

Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.


Last time I covered C# JSON serialization, I only showcased the Newtonsoft.Json library. This time, I will also show the System.Text.Json way.

You might want to (de)serialize enums as strings, rather than numeric values. Since C# does not support enums with an underlying type of string, you need to do some extra work. Namely, you have to annotate each value using the EnumMember annotation and then select the correct converter, once again using annotations.

using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

public enum Mood
{
    [EnumMember(Value = "happy")]
    Happy,
    [EnumMember(Value = "sad")]
    Sad,
}

public class Object
{
    [JsonProperty("mood")]

    [JsonConverter(typeof(StringEnumConverter))]
    public Mood Mood { get; set; }
}

public static class Program
{
    public static void Main()
    {
        string json = JsonConvert.SerializeObject(new Object
        {
            Mood = Mood.Sad
        });

        Console.WriteLine(json);
        // {"mood":"sad"}
        Console.WriteLine(JsonConvert.DeserializeObject<Object>(json)!.Mood);
        // Sad
    }
}

However, System.Text.Json doesn’t support EnumMember annotations out of the box. It takes the literal name of the property instead. You can play with capitalization using options object, but that’s it. Or you can write your own converter. Or you can just use one of the dozen converters from the Internet that do the hard work for you.

using System.Runtime.Serialization;
using System.Text.Json.Serialization;

public enum Mood
{
    [EnumMember(Value = "happy")]
    Happy,
    [EnumMember(Value = "sad")]
    Sad,
}

public class Object
{
    [JsonPropertyName("mood")]
    // To use EnumMember annotations, install Macross.Json.Extensions nuget
    // and use a different converter
    // [JsonConverter(typeof(JsonStringEnumMemberConverter))]
    [JsonConverter(typeof(JsonStringEnumConverter))]
    public Mood Mood { get; set; }
}

public static class Program
{
    public static void Main()
    {
        Object obj = new()
        {
            Mood = Mood.Sad,
        };

        string json = System.Text.Json.JsonSerializer.Serialize(obj);
        Console.WriteLine(json);
        // {"mood":"Sad"}
        Console.WriteLine(System.Text.Json.JsonSerializer.Deserialize<Object>(json)!.Mood);
        // Sad
    }
}

Want more #dotnet & #csharp deep dives?

Join 5,973+ developers sharing real benchmarks, code breakdowns, and projects. Free forever.

Part 28 of 31 in Tuesday Coding Tips

2 Comments

2 votes
0

More Posts

Tuesday Coding Tip 06 - Explicit template instantiation

Jakub Neruda - Apr 7

Tuesday Coding Tip 02 - Template with type-specific API

Jakub Neruda - Mar 10

Tuesday Coding Tip 26 — JSON (de)serialization in C#

Jakub Neruda - Oct 13

Tuesday Coding Tip 27 — Aliasing and ‘using’ in C++

Jakub Neruda - Oct 20

Tuesday Coding Tip 05 - Object initialization in C++

Jakub Neruda - Mar 31
chevron_left
2.1k Points • 125 Badges
Brno, Czech Republic • linkedin.com/in/jakub-neruda
42Posts
36Comments
22Connections
Experienced C++ developer, team lead and hobby gamedev. I enjoy writing stuff about C++, clean code, clean architecture, and game development.

Related Jobs

Commenters (This Week)

13 comments
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!