Creating Custom Converters for .NET System.Text.Json

bytedev
2 min readAug 18, 2021

--

System.Text.Json is Microsoft’s equivalent package to the very popular Newtonsoft.Json for JSON serialization. System.Text.Json is often measured as being more performant but does not currently have as many features. One feature System.Text.Json does currently have though is the ability to add custom converters. A converter is a class that converts a .NET value to and from JSON. System.Text.Json has a number of built in converters but through defining our own we can instruct the serializer to handle values in the exact way we want.

All examples are in C# and it’s assumed that the reader has used System.Text.Json before for JSON serialization.

JSON Data Types

Before jumping into the implementation and usage of custom converters it’s worth noting what data types we can possibly be converting to/from in JSON.

JSON has a much smaller set of data types than .NET. These are:

  • Number (integer or floating point)
  • String
  • Object (JSON object)
  • Array
  • Boolean (true or false)
  • null

For some simple examples of each JSON data type check out the page on W3Schools.

Implementing a Custom Converter

When implementing our own custom converter we must do three things:

  • Define our own custom converter class and make it inherit from JsonConverter<T> where T is the .NET type we want to convert to/from JSON.
  • Within our new custom class override the implementation of the Read method. This method is called on deserialization (reading JSON).
  • Within our new custom class override the implementation of the Write method. This method is called on serialization (writing JSON).

The following simple example (used in a .NET Standard 2.0 assembly) demonstrates how we might convert a JSON number that represents a Unix Epoch time stamp (number of seconds past the Unix epoch 00:00:00 UTC on 1 January 1970) to a .NET DateTime.

Converting Unix epoch time to/from DateTime

Unit Testing the Custom Converter

Now we have our custom converter we can use it during serialization/deserialization by adding the converter to the options object we can pass to the JsonSerialize.Serialize or JsonSerializer.Deserialize methods.

The following unit tests demonstrate usage of the custom converter and tests the conversion from a JSON number value to a .NET DateTime and back again:

Unit tests for the Unix epoch time/DateTime converter

--

--

bytedev
bytedev