https://stackoverflow.com/questions/65972825/c-sharp-deserializing-nested-json-to-nested-dictionarystring-object

CSharp · Console

/Program.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Dynamic;

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

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

//https://stackoverflow.com/questions/65972825/c-sharp-deserializing-nested-json-to-nested-dictionarystring-object

#nullable enable

	public class ObjectAsPrimitiveConverter : JsonConverter<object>
	{
		FloatFormat FloatFormat { get; init; }
		UnknownNumberFormat UnknownNumberFormat { get; init; }
		ObjectFormat ObjectFormat { get; init; }

		public ObjectAsPrimitiveConverter() : this(FloatFormat.Double, UnknownNumberFormat.Error, ObjectFormat.Expando) { }
		public ObjectAsPrimitiveConverter(FloatFormat floatFormat, UnknownNumberFormat unknownNumberFormat, ObjectFormat objectFormat)
		{
			this.FloatFormat = floatFormat;
			this.UnknownNumberFormat = unknownNumberFormat;
			this.ObjectFormat = objectFormat;
		}
		
		public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options)
		{
			if (value == null)
				writer.WriteNullValue();
			else if (value.GetType() == typeof(object))
			{
				writer.WriteStartObject();
				writer.WriteEndObject();
			}
			else
			{
				JsonSerializer.Serialize(writer, value, value.GetType(), options);
			}
		}
		
		public override object? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
		{
			switch (reader.TokenType)
			{
				case JsonTokenType.Null:
					return null;
				case JsonTokenType.False:
					return false;
				case JsonTokenType.True:
					return true;
				// If you want to, you could add a heuristic that automatically recognizes and returns DateTime values here:
				//case JsonTokenType.String when reader.TryGetDateTime(out var dt):
				//	return dt;
				// Or if you would prefer not to lose time zone info, you could add automatic DateTimeOffset recognition here:
				//case JsonTokenType.String when reader.TryGetDateTimeOffset(out var dt):
				//	return dt;
				case JsonTokenType.String:
					return reader.GetString();
				case JsonTokenType.Number:
				{
					if (reader.TryGetInt32(out var i))
						return i;
					if (reader.TryGetInt64(out var l))
						return l;
					// BigInteger could be added here.
					if (FloatFormat == FloatFormat.Decimal && reader.TryGetDecimal(out var m))
						return m;
					else if (FloatFormat == FloatFormat.Double && reader.TryGetDouble(out var d))
						return d;
					using var doc = JsonDocument.ParseValue(ref reader);
					if (UnknownNumberFormat == UnknownNumberFormat.JsonElement)
						return doc.RootElement.Clone();
					throw new JsonException(string.Format("Cannot parse number {0}", doc.RootElement.ToString()));
				}
				case JsonTokenType.StartArray:
				{
					var list = new List<object?>();
					while (reader.Read())
					{
						switch (reader.TokenType)
						{
							default:
								list.Add(Read(ref reader, typeof(object), options));
								break;
							case JsonTokenType.EndArray:
								return list;
						}
					}
					throw new JsonException();
				}
				case JsonTokenType.StartObject:
					var dict = CreateDictionary();
					while (reader.Read())
					{
						switch (reader.TokenType)
						{
							case JsonTokenType.EndObject:
								return dict;
							case JsonTokenType.PropertyName:
								var key = reader.GetString()!;
								reader.Read();
								dict.Add(key, Read(ref reader, typeof(object), options));
								break;
							default:
								throw new JsonException();
						}
					}
					throw new JsonException();
				default:
					throw new JsonException(string.Format("Unknown token {0}", reader.TokenType));
			}
		}
		
		protected virtual IDictionary<string, object?> CreateDictionary() => 
			ObjectFormat == ObjectFormat.Expando ? new ExpandoObject() : new Dictionary<string, object?>();
	}

	public enum FloatFormat
	{
		Double,
		Decimal,
	}

	public enum UnknownNumberFormat
	{
		Error,
		JsonElement,
	}
	
	public enum ObjectFormat
	{
		Expando,
		Dictionary,
	}

    class TestClass
    {
        public static void Test()
        {
			var json = GetJson();
			
			var options = new JsonSerializerOptions
			{
				Converters = { new ObjectAsPrimitiveConverter(floatFormat : FloatFormat.Double, unknownNumberFormat : UnknownNumberFormat.Error, objectFormat : ObjectFormat.Expando) },
				WriteIndented = true,
			};
			dynamic d = JsonSerializer.Deserialize<dynamic>(json, options)!;
			Assert.AreEqual(true, d.boolean);
			Assert.AreEqual("string", d.String);
			Assert.AreEqual(null, d.Null);
			Assert.AreEqual(3.14, d.Double);
			Assert.AreEqual(100101, d.Int);
			Assert.AreEqual(9223372036854775800L, d.Long);
			Assert.IsTrue((new object [] { "a", "b", "c" }).SequenceEqual((IEnumerable<object>)d.ArrayOfStrings));

			var reserialized = JsonSerializer.Serialize(d, options);
			
			// Test that the round-trip to dynamic results in the same re-serialized JSON as the round-trip to JsonElement:
			var element = JsonSerializer.Deserialize<JsonElement>(json);
			var elementJson = JsonSerializer.Serialize(element, new JsonSerializerOptions { WriteIndented = true });
			
			Assert.AreEqual(elementJson, reserialized);

			Assert.AreEqual("{}", JsonSerializer.Serialize(new object(), options));
			
			Console.WriteLine("Re-serialized JSON:");
			Console.WriteLine(reserialized);
		}	
		
		static string GetJson() =>
			@"{
			""boolean"":true,
			""String"":""string"",
			""Null"":null,
			""Double"":3.14,
			""Int"": 100101,
			""Long"": 9223372036854775800,
			""ArrayOfStrings"":[""a"",""b"",""c""],
			""DateTimeOffset"" : ""1996-12-19T16:39:57-08:00"",
			""web-app"": {
  ""servlet"": [   
    {
      ""servlet-name"": ""cofaxCDS"",
      ""servlet-class"": ""org.cofax.cds.CDSServlet"",
      ""init-param"": [{
        ""configGlossary:installationAt"": ""Philadelphia, PA"",
        ""configGlossary:adminEmail"": ""[email protected]"",
        ""configGlossary:poweredBy"": ""Cofax"",
        ""configGlossary:poweredByIcon"": ""/images/cofax.gif"",
        ""configGlossary:staticPath"": ""/content/static"",
        ""templateProcessorClass"": ""org.cofax.WysiwygTemplate"",
        ""templateLoaderClass"": ""org.cofax.FilesTemplateLoader"",
        ""templatePath"": ""templates"",
        ""templateOverridePath"": """",
        ""defaultListTemplate"": ""listTemplate.htm"",
        ""defaultFileTemplate"": ""articleTemplate.htm"",
        ""useJSP"": false,
        ""jspListTemplate"": ""listTemplate.jsp"",
        ""jspFileTemplate"": ""articleTemplate.jsp"",
        ""cachePackageTagsTrack"": 200,
        ""cachePackageTagsStore"": 200,
        ""cachePackageTagsRefresh"": 60,
        ""cacheTemplatesTrack"": 100,
        ""cacheTemplatesStore"": 50,
        ""cacheTemplatesRefresh"": 15,
        ""cachePagesTrack"": 200,
        ""cachePagesStore"": 100,
        ""cachePagesRefresh"": 10,
        ""cachePagesDirtyRead"": 10,
        ""searchEngineListTemplate"": ""forSearchEnginesList.htm"",
        ""searchEngineFileTemplate"": ""forSearchEngines.htm"",
        ""searchEngineRobotsDb"": ""WEB-INF/robots.db"",
        ""useDataStore"": true,
        ""dataStoreClass"": ""org.cofax.SqlDataStore"",
        ""redirectionClass"": ""org.cofax.SqlRedirection"",
        ""dataStoreName"": ""cofax"",
        ""dataStoreDriver"": ""com.microsoft.jdbc.sqlserver.SQLServerDriver"",
        ""dataStoreUrl"": ""jdbc:microsoft:sqlserver://LOCALHOST:1433;DatabaseName=goon"",
        ""dataStoreUser"": ""sa"",
        ""dataStorePassword"": ""dataStoreTestQuery"",
        ""dataStoreTestQuery"": ""SET NOCOUNT ON;select test='test';"",
        ""dataStoreLogFile"": ""/usr/local/tomcat/logs/datastore.log"",
        ""dataStoreInitConns"": 10,
        ""dataStoreMaxConns"": 100,
        ""dataStoreConnUsageLimit"": 100,
        ""dataStoreLogLevel"": ""debug"",
        ""maxUrlLength"": 500}]
    },
    {
      ""servlet-name"": ""cofaxEmail"",
      ""servlet-class"": ""org.cofax.cds.EmailServlet"",
      ""init-param"": {
      ""mailHost"": ""mail1"",
      ""mailHostOverride"": ""mail2""}
    },
    {
      ""servlet-name"": ""cofaxAdmin"",
      ""servlet-class"": ""org.cofax.cds.AdminServlet""},
 
    {
      ""servlet-name"": ""fileServlet"",
      ""servlet-class"": ""org.cofax.cds.FileServlet""
    },
    {
      ""servlet-name"": ""cofaxTools"",
      ""servlet-class"": ""org.cofax.cms.CofaxToolsServlet"",
      ""init-param"": {
        ""templatePath"": ""toolstemplates/"",
        ""log"": 1,
        ""logLocation"": ""/usr/local/tomcat/logs/CofaxTools.log"",
        ""logMaxSize"": """",
        ""dataLog"": 1,
        ""dataLogLocation"": ""/usr/local/tomcat/logs/dataLog.log"",
        ""dataLogMaxSize"": """",
        ""removePageCache"": ""/content/admin/remove?cache=pages&id="",
        ""removeTemplateCache"": ""/content/admin/remove?cache=templates&id="",
        ""fileTransferFolder"": ""/usr/local/tomcat/webapps/content/fileTransferFolder"",
        ""lookInContext"": 1,
        ""adminGroupID"": 4,
        ""betaServer"": true}}],
  ""servlet-mapping"": {
    ""cofaxCDS"": ""/"",
    ""cofaxEmail"": ""/cofaxutil/aemail/*"",
    ""cofaxAdmin"": ""/admin/*"",
    ""fileServlet"": ""/static/*"",
    ""cofaxTools"": ""/tools/*""},
 
  ""taglib"": {
    ""taglib-uri"": ""cofax.tld"",
    ""taglib-location"": ""/WEB-INF/tlds/cofax.tld""}}}";
		
	}

	public class Program
	{
		public static void Main()
		{
			Console.WriteLine("Environment version: {0} ({1}), {2}", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , Environment.Version, Environment.OSVersion);
			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;
			}
		}
	}
;