[Fork] https://stackoverflow.com/questions/66495660/net-5-0-signature-change-of-system-text-json-jsonserializer-deserialize

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.Text.Json;
using System.Text.Json.Serialization;

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

//https://stackoverflow.com/questions/60907741/jsonconverter-determine-whether-propertyvalue-is-a-decimal-or-number

#nullable enable

	public sealed class DictionaryConverter : JsonConverter<IDictionary<string, object>>
	{
		public override IDictionary<string, object> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
			// Assert we are currently at the beginning of an object
			if (reader.TokenType != JsonTokenType.StartObject)
				throw new JsonException(string.Format("Unexpected token {0}", reader.TokenType));
		
            IDictionary<string, object> output = new Dictionary<string, object>();

            while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)
            {
                string propertyName = reader.GetString()!;
                reader.Read();
                object? propertyValue;

                switch (reader.TokenType)
                {
                    case JsonTokenType.Number:
						if (reader.TryGetInt64(out var l))
							propertyValue = l;
						else if (reader.TryGetDecimal(out var d))
							propertyValue = d;
						else
						{
							// Either store the value as a string, or throw an exception.
							using var doc = JsonDocument.ParseValue(ref reader);
							propertyValue = doc.RootElement.ToString();
							throw new JsonException(string.Format("Cannot parse number: {0}", propertyValue));
						}
                        break;
                    case JsonTokenType.String:
                        if (reader.TryGetDateTime(out var dt))
                            propertyValue = dt;
                        else
                            propertyValue = reader.GetString();
                        break;
                    case JsonTokenType.True:
                    case JsonTokenType.False:
                        propertyValue = reader.GetBoolean();
                        break;
					case JsonTokenType.Null:
						propertyValue = null;
						break;
					default:
						// An unexpected token type such as an object or array.
						// You must either skip it or throw an exception.
						reader.Skip();
						propertyValue = null;
						throw new JsonException(string.Format("Unexpected token {0}", reader.TokenType));
						//break;
                }
				// Since your converter is of type IDictionary<string, object> I assume you don't want to allow null values.
				// If you do want to allow null values you should declare it as IDictionary<string, object?>
				if (propertyValue == null)
					throw new JsonException("null value");
                output.Add(propertyName, propertyValue);
            }

            return output;
        }
		
		public override void Write(Utf8JsonWriter writer, IDictionary<string, object> value, JsonSerializerOptions options) =>
			// Generate a default serialization without using the converter
			JsonSerializer.Serialize(writer, value, options.CopyAndRemoveConverter(GetType()));
	}

	public static class JsonSerializerExtensions
	{
		public static JsonSerializerOptions CopyAndRemoveConverter(this JsonSerializerOptions options, Type converterType)
		{
			var copy = new JsonSerializerOptions(options);
			for (var i = copy.Converters.Count - 1; i >= 0; i--)
				if (copy.Converters[i].GetType() == converterType)
					copy.Converters.RemoveAt(i);
			return copy;
		}
	}

    class TestClass
    {
        public static void Test()
        {
			var dictionary = new Dictionary<string, object>()
			{
				{"a", 1.100100m },
				{"d", long.MaxValue },
				{"s", "some string" },
				{"date", new DateTime(2021, 3, 3, 10, 10, 10) },
				{"true", true},
				{"false", false},
			};

			var options = new JsonSerializerOptions
			{
				WriteIndented = true,
				Converters = { new DictionaryConverter() },
			};
			
			var json = JsonSerializer.Serialize(dictionary, options);
			
			Console.WriteLine(json);
			
			var dictionary2 = JsonSerializer.Deserialize<IDictionary<string, object>>(json, options);
			
			dictionary2.Dump();
			
			Assert.IsTrue(dictionary2 != null);
			Assert.IsTrue(dictionary.Keys.SequenceEqual(dictionary2!.Keys));
			Assert.IsTrue(dictionary.Values.SequenceEqual(dictionary2!.Values));
		}
	}

	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 "";
		}
	}
;