Enumeration class and JSON Serialization

Posted by

This is the second post in the Series: Enumeration classes – DDD and beyond. If you have jumped here right in and are new to the Enumeration classes, I suggest going through the previous post first.

In part 1, I gave an introduction to Enumeration class and what problem it solves. In this and upcoming posts, I will explain how we can use Enumeration class for advanced scenarios. This post would cover how to we can serialize an Enumeration class.

A disclaimer before I go further:

While the Enumeration class is an excellent alternate to an Enum, it brings along a fair deal of complexity. Enumeration class solves specific-business scenarios and may not be fit for general purposes. Please evaluate if it suits your needs before adopting the Enumeration class.

Source Code

You can find the source code of this series at this GitHub repository.

Why serialize an Enumeration Class?

There can be a few reasons you may need to serialize and deserialize an Enumeration class, such as:

  • Saving and retrieving your domain object in No-SQL DBs like Cosmos, Raven DB, etc.
  • Using Enumeration class in the request body and response of a Web API.
  • Publishing and retrieving an object with Enumeration class from a message bus.

Let us go back to our PaymentType example from our last post.

Unlike an Enum, PaymentType is a class with static readonly members. We would need a custom logic or converter to serialize it to JSON and deserialize it back.

Version 1 – Using System.Text.Json

We can extend System.Text.Json –>JsonConverter of to serialize and deserialize an Enumeration class.

Version 2 – Using Newtonsoft.Json

Unfortunately, System.Text.Json has still not reached feature parity to Newtonsoft.Json. As a result, so often, we fall back to Newtonsoft.Json.

Here is the Newtonsoft.Json version of JsonConverter

Usage

Let us consider a class Transaction with property PaymentType.

We can serialize and serialize the Transaction class using EnumerationJsonConverter, as shown in the below test:

Here is the JSON output:

I hope you enjoyed this post and learning about how you can create a custom JSON converter to serialize an Enumeration class.