Tuesday, May 10, 2022

Fix the issue with incorrect BigInteger serialization of MVC

When I wrote an webAPI method that returns a structure with BigInteger in it (used a lot in blockchain development) it turned out that the output looks as follows:



It looks like the default serializer of BigInteger used by the MVC works in a bit strange way.

There was a way of course to add decorators to the BigInteger data members of the structure that I wanted to serialize, but I use Nethereum and the structure was automatically generated by a Nethereum tool (which is quite handy, by the way). So I wanted to find a way to override the default behavior of the JSON serializer for the BigInteger type.

Took me some time to understand how to do it, but in the end it all makes sense and is quite simple:

1. Created a class that inherits from JsonConverter<BigInteger> as follows:

using System.Numerics;

using System.Text.Json;
using System.Text.Json.Serialization;

namespace AkwaWeb
{
    public class BigIntegerJsonConverter : JsonConverter<BigInteger>
    {
        public override BigInteger Read(
                   ref Utf8JsonReader reader,
                   Type typeToConvert,
                   JsonSerializerOptions options) =>
                       BigInteger.Parse(reader.GetString()!);
        public override void Write(
            Utf8JsonWriter writer,
            BigInteger val,
            JsonSerializerOptions options) =>
                writer.WriteStringValue(val.ToString());
    }
}

2. Registered it during the system initialization as follows:

builder.Services.AddMvc().AddJsonOptions(options =>
{
   options.JsonSerializerOptions.Converters.Add(new AkwaWeb.BigIntegerJsonConverter());
});

3. Et voila