The .NET Weekly is brought to you by:
The Developer Ecosystem in 2023: Key Trends for C# Explore the key trends of today's C# and .NET development in the State of Developer Ecosystem 2023 report by JetBrains, which also includes commentary from the wider .NET community
About today’s newsletter :
What are JSON convertors
Custom JSON conversion scenarios
How to create them in .NET 6
How can we create convertors that can accept attributes
What is a JSON Convertor
A JSON converter is a class designed to facilitate the conversion of objects or values to and from JSON format.
In the context of working with APIs, there are frequent scenarios where the transformation of values received from HTTP clients into our preferred data types becomes necessary. In such situations convertors can play a vital role.
Custom JSON Conversion Scenarios
There are no hard code rule for this thing but here are few cases when I find making convertors helpful :
1/ Enum Type Handling
2/ Custom Date Formatting
3/ Localization of Date and Number Formats
How to create JSON Convertor in .NET
I am fan of System.Text.Json so I would demonstrate how to create convertors using that.
To make it more understandable let’s make a scenario, suppose we have a property in our response model named Status Code which is returned from API we are calling.
Problem is it could be int and string both we are not sure what will come. One could suggest that let’s use dynamic data type.
But I don’t like it, I will go for a JSON convertor and make data type of StatusCode as string. So my convertor would look like this.
If you don’t like the example pardon, just focus on understanding the concept. Now we can apply this convertor like this :
What exactly is happening in convertor code ?
Read Method:
The Read
method is responsible for converting JSON data into a string when your program is reading or deserializing JSON.
Write Method:
The Write
method is responsible for converting a string into the appropriate JSON format when your program is writing or serializing JSON
Another converter that overrides default serialization for an existing data type. The converter uses mm/dd/yyyy format for DateTimeOffset
properties.
Convertors that accepts Parameters + Factory
Sometime we need to send parameters to our convertor, you might be thinking how can we handle it in convertors. Quite simple follow these steps :
Create convertors for each scenerio like we did in previous step.
Now create another class which acts like a factory, this class will implement JsonConverterAttribute
Utilise reflection here, check the types with typeOf and call your desired convertors.
In some cases convertors don’t work by just putting it over the property, we have to add it in serialization options. I mostly work with Refit and I don’t find need of adding it. If due to some reasons it does not work one can add it like this :
Now one can use these options for serialization/de-serialization.
Summary
A JSON converter is a specialized class designed to handle the conversion of objects or values to and from JSON format
Common scenarios where custom JSON converters are beneficial include handling Enum types, implementing custom date formatting, and localizing date and number formats.
In the .NET , using System.Text.Json, creating a JSON converter involves defining a class that overrides default serialization or deserialization for a specific data type.
The Read method within the converter is responsible for deserializing JSON and write for Serializing
For cases where converters require parameters, a factory class is introduced, implementing the JsonConverterAttribute, and the desired parameters are passed through the constructor of the converter class.
In some situations, converters may need to be explicitly added to serialization options. This can be achieved by configuring serialization options with the custom converter, allowing for effective customization of serialization and deserialization processes.
Whenever you’re ready, there are 3 ways I can help you:
Promote yourself to 8500+ subscribers by Sponsoring my Newsletter
Get a FREE eBook from Gumroad that contains 30 .NET Tips (3K+ downloads)
Become a Patron (If my content was helpful) and get access to 180+ .NET Questions and Answers
Special Offers
Pragmatic Clean Architecture: Learn how to confidently ship well-architected production-ready apps using clean architecture. [ 10% discount with promo code MUWAS]
Ultimate ASP.NET Core Web API Second Edition - Premium Package [10% discount with promo code 9s6nuez]