Create Custom Int32Converter for System.Text.Json

In this article, we will see how to create an Int32Converter useful for the deserializing string to primitives Int32, Bool, double, etc properties as required.

Today in this article, we will cover below aspects,

We shall be following the below high-level steps to create a converter using a basic pattern,

  • Override the Read method
  • Override the Write method
  • Register a Custom converter as a serializer option
  • Perform serialize/deserialize

As we know the new .NET /ASP.NET Core 3.1 or .NET 5.0 framework has removed the dependency on JSON.NET and uses its own JSON serializer i.e. ‘System.Text.Json‘.

Deserialization with the non-string value received for a string field shall result in a JsonException in .NET Core.

There are known limitations in the System.Text.Json serializer which are as per specification and design. That means the best alternative is to write a custom converter.

System.Text.Json doesn’t deserialize non-string values like Int, Boolean, and other primitives into string properties.

Any non-string value conversion produces the below exception,

System.Text.Json.JsonException: ‘The JSON value could not be converted to System.Int32

Int32Converter for System.Text.Json

To overcome the issue, one can write CustomConverter to allow literal integer, double, or true or false or Number conversion to string conversion.

Below Read() method Reads and converts the JSON to type T.

JsonConverter<T> Converts an object or value to or from JSON.

JsonTokenType lets you define JSON tokens that make up a final JSON text.

  if (reader.TokenType == JsonTokenType.String)
            {
                string stringValue = reader.GetString();
                if (int.TryParse(stringValue, out int value))
                {
                    return value;
                }
            }

Create Custom Converter

Here is the complete code,

public class Int32Converter : System.Text.Json.Serialization.JsonConverter<int>
    {
        public override int Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            if (reader.TokenType == JsonTokenType.String)
            {
                string stringValue = reader.GetString();
                if (int.TryParse(stringValue, out int value))
                {
                    return value;
                }
            }
            else if (reader.TokenType == JsonTokenType.Number)
            {
                return reader.GetInt32();
            }

            throw new System.Text.Json.JsonException();
        }

        public override void Write(Utf8JsonWriter writer, int value, JsonSerializerOptions options)
        {
            writer.WriteNumberValue(value);
        }
    }

Please extend the converter for further type conversion if needed.

Let now deserialize the below JSON into the type expecting string for integers

Let’s use the below JSON type example,

Create Custom Int32Converter for SystemTextJson

Target Type Customer as below,

Create Custom Int32Converter for SystemTextJson

Let’s register the Custom String Converted using JsonSerializerOptions.

Int32Converter can be used to pass as the second argument to JsonSerializer.Deserialize method.

Using Int32Converter

           var serializeOptions = new JsonSerializerOptions();

            serializeOptions.Converters.Add(new StringConverter());

            Customer empObject = JsonSerializer.Deserialize<Customer>(jsonOutPut, serializeOptions);


Finally, conversion is successful,

Create Custom Int32Converter for SystemTextJson

Applying Custom Converter globally

If using API using ASP.NET Core application then one can define the logic globally in the API pipeline using startup.cs update for AddJsonOptions as below,

services.AddControllers().AddJsonOptions(options =>
{
  options.JsonSerializerOptions.Converters.Add(new Int32Converter());
});

That’s All, Enjoy Coding !!

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.