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

●5 ●16 ●83
calendar_today ago • 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
    }
}
Part 28 of 28 in Tuesday Coding Tips

2 Comments

2 votes
0
🔥 Join developers growing publicly
Share your knowledge, build in public, and grow your developer presence with a global community.

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
1.9k Points • 104 Badges
Brno, Czech Republic • linkedin.com/in/jakub-neruda
35Posts
35Comments
21Connections
Experienced C++ developer, team lead and hobby gamedev. I enjoy writing stuff about C++, clean code, clean architecture, and game development.

Related Jobs

View all jobs →

Commenters (This Week)

4 comments
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!