- Part 1 – https://ankitvijay.net/2020/05/21/introduction-enumeration-class/
- Part 2: Enumeration class and JSON Serialization (this post)
- Part 3: https://ankitvijay.net/2020/06/14/enumeration-class-query-string/
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.
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
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.