Enum Serialization: System.Text.Json vs Utf8Json vs Jil vs Newtonsoft

I was reading about the new System.Text.Json in .net core 3 and comparing its speed to other libraries. You can read more about it here if you’re interested. To put it shortly, the new serializer is faster then Newtonsoft but not as fast as others. Also the enum serialization between different libraries can be inconsistent. The same thing goes for structs. Some of these differences are related to speed. Others are related to the ability to serialize or how the output is formatted. But in this post I’m going to compare how enum serialization is different between these libraries. I also going to show you how you can change the output.

Enum Serialization differences between serialization libraries in .Net

Suppose we have an enum like the one below and we want to serialize it.

We created an object what looks like this.

Days meetingDays = Days.Monday | Days.Wednesday | Days.Friday;

System.Text.Json

Serialize it as “21”

Utf8Json

Serialize it as “Monday, Wednesday, Friday”

Jil

Serialize it as “Monday, Wednesday, Friday”

Newtonsoft

Serialize it as “21”

Depend on our use case, we might expect different result from these libraries. But if the result does not conform to what we want, we have the option to change it.

How to change enum serialization for System.Text.Json

If we intend to change how System.Text.Json serialize enum we can do that by decorating our enum by an attribute. We can use [JsonConverter(typeof(JsonStringEnumConverter))] on top of our enum definition. After doing that what we receive from serializer is “Monday, Wednesday, Friday” like the other libraries.

How to change enum serialization for Newtonsoft

Much like what we did with System.Text.Json, we can use another attribute for Newtonsoft. But this time we need decorate our enum with [JsonConverter(typeof(StringEnumConverter))] attribute. By doing so, what we receive from serializer will be “Monday, Wednesday, Friday”.

Summary

In this post, I discussed how enum serialization is different between different libraries in .net. We also saw how we can change that output if we wanted to.

Share...
 

Hamid Mosalla

Hi, I'm Hamid ("Arman"). I'm a software developer with 8+ years of experience in C#, .NET Core, Software Architecture and Web Development. I enjoy creating dev tools, contributing to open-source projects, and sharing insights on my blog. Outside of tech, I’m into indie cinema, classical music and abstract art.

 

Leave a Reply

Your email address will not be published. Required fields are marked *