[Fork] https://stackoverflow.com/questions/64788895/serialising-biginteger-using-system-text-json

CSharp · Console

/Program.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters;
using System.IO;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Collections.ObjectModel;
using System.Numerics;

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

using NUnit.Framework; // Throws NUnit.Framework.AssertionException

//https://stackoverflow.com/questions/64788895/serialising-biginteger-using-system-text-json

	public class BigIntegerConverter : JsonConverter<BigInteger>
	{
		public override BigInteger Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
		{
			if (reader.TokenType != JsonTokenType.Number)
				throw new JsonException(string.Format("Found token {0} but expected token {1}", reader.TokenType, JsonTokenType.Number ));
			using var doc = JsonDocument.ParseValue(ref reader);
			return BigInteger.Parse(doc.RootElement.GetRawText(), NumberFormatInfo.InvariantInfo);
		}

		public override void Write(Utf8JsonWriter writer, BigInteger value, JsonSerializerOptions options)
		{
			var s = value.ToString(NumberFormatInfo.InvariantInfo);
			using var doc = JsonDocument.Parse(s);
			doc.WriteTo(writer);
		}
	}

    class TestClass
    {
        public static void Test()
		{
			var options = new JsonSerializerOptions();
			options.Converters.Add(new BigIntegerConverter());
			var s = JsonSerializer.Serialize(new {foo = new BigInteger(ulong.MaxValue) + 1}, options);			
			Assert.AreEqual(@"{""foo"":18446744073709551616}", s);
			
			Console.WriteLine(s);
			var i = new BigInteger(ulong.MaxValue) + 1;
			Test(i);
			Test(i * i * i);
			Test(i * i * i * i * i * i);
			Test(-i * i * i * i * i * i);
		}
		
        public static void Test(BigInteger i)
        {			
			var options = new JsonSerializerOptions
			{
				Converters = { new BigIntegerConverter() },
			};
			
			var json = JsonSerializer.Serialize(i, options);			
			
			Console.WriteLine(json);
			
			var i2 = JsonSerializer.Deserialize<BigInteger>(json, options);
			
			Assert.IsTrue(i == i2);
		}	
	}

	public class Program
	{
		public static void Main()
		{
			Console.WriteLine("Environment version: {0} ({1})", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , GetNetCoreVersion());
			Console.WriteLine("System.Text.Json version: " + typeof(JsonSerializer).Assembly.FullName);
			Console.WriteLine();

			try
			{
				TestClass.Test();
			}
			catch (Exception ex)
			{
				Console.WriteLine("Failed with unhandled exception: ");
				Console.WriteLine(ex);
				throw;
			}
		}
		
		public static string GetNetCoreVersion()
		{
			//https://techblog.dorogin.com/how-to-detect-net-core-version-in-runtime-ecd65ad695be
			//
			var assembly = typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly;
			var assemblyPath = assembly.Location.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
			int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App");
			if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2)
				return assemblyPath[netCoreAppIndex + 1];
			return null;
		}
	}
;