https://stackoverflow.com/questions/76276372/json-deserialize-in-one-data-as-array-and-in-one-as-json-object-coming-tricky-no

CSharp · Console

/Program.cs

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

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;	

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

//https://stackoverflow.com/questions/76276372/json-deserialize-in-one-data-as-array-and-in-one-as-json-object-coming-tricky-no

	public class TestClass
    {
        public List<Variant> variants { get; set; } = new ();
    }

    public class Variant
    {
        public string name { get; set; }
        public string description { get; set; }
		
		[JsonConverter(typeof(JsonSingleOrEmptyArrayConverter<Dictionary<string, List<Image>>>))]
		public Dictionary<string, List<Image>> images { get; set; } = new ();
    }

    public class Image
    {
        public string id { get; set; }
        public string product_id { get; set; }
    }

	public class JsonSingleOrEmptyArrayConverter<T> : JsonConverter where T : class
	{
		// Copied from this answer https://stackoverflow.com/a/53219877
		// To https://stackoverflow.com/questions/53219668/cannot-deserialize-the-current-json-object-empty-array
		public override bool CanConvert(Type objectType)
		{
			return typeof(T).IsAssignableFrom(objectType);
		}

		public override bool CanWrite { get { return false; } }

		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			var contract = serializer.ContractResolver.ResolveContract(objectType);
			// Allow for dictionary contracts as well as objects contracts, since both are represented by 
			// an unordered set of name/value pairs that begins with { (left brace) and ends with } (right brace).
			if (!(contract is Newtonsoft.Json.Serialization.JsonObjectContract 
				  || contract is Newtonsoft.Json.Serialization.JsonDictionaryContract))
			{
				throw new JsonSerializationException(string.Format("Unsupported objectType {0} at {1}.", objectType, reader.Path));
			}

			switch (reader.SkipComments().TokenType)
			{
				case JsonToken.StartArray:
					{
						int count = 0;
						while (reader.Read())
						{
							switch (reader.TokenType)
							{
								case JsonToken.Comment:
									break;
								case JsonToken.EndArray:
									// You might want to allocate an empty object here if existingValue is null
									// If so, do
									// return existingValue ?? contract.DefaultCreator();
									return existingValue;
								default:
									{
										count++;
										if (count > 1)
											throw new JsonSerializationException(string.Format("Too many objects at path {0}.", reader.Path));
										existingValue = existingValue ?? contract.DefaultCreator();
										serializer.Populate(reader, existingValue);
									}
									break;
							}
						}
						// Should not come here.
						throw new JsonSerializationException(string.Format("Unclosed array at path {0}.", reader.Path));
					}

				case JsonToken.Null:
					return null;

				case JsonToken.StartObject:
					existingValue = existingValue ?? contract.DefaultCreator();
					serializer.Populate(reader, existingValue);
					return existingValue;

				default:
					throw new InvalidOperationException("Unexpected token type " + reader.TokenType.ToString());
			}
		}

		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
			throw new NotImplementedException();
		}
	}

	public static partial class JsonExtensions
	{
		public static JsonReader SkipComments(this JsonReader reader)
		{
			while (reader.TokenType == JsonToken.Comment && reader.Read())
				;
			return reader;
		}
	}

    class TestHarness
    {
        public static void Test()
        {
			var json = GetJson();
			
			Console.WriteLine("Input JSON:");
			Console.WriteLine(JToken.Parse(GetJson()));
			
			var root = JsonConvert.DeserializeObject<TestClass>(json);

			var json2 = JsonConvert.SerializeObject(root, Formatting.Indented);

			foreach (var variant in root.variants)
			{
				Console.WriteLine($"Images for {variant.name}:");
				foreach (var pair in variant.images)
				{
					Console.WriteLine($"  For color {pair.Key}:");
					foreach (var image in pair.Value)
						Console.WriteLine($"    id = {image.id}");
				}
			}
			
			Console.WriteLine("Re-serialized {0}:", root);
			Console.WriteLine(json2);
		}	
		
		static string GetJson() =>
"""
{ "variants": [
                {
                    "name": "test1",
                    "description": "test1",
                    "images": []
                },
               {
                    "name": "test2",
                    "description": "test2",
                    "images": {
                        "WHITE": [
                            {
                                "id": "ttest",
                                "product_id": "ttest",
                            }
                        ]
                    }
               }
            ]
}
""";
	}

	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("{0} version: {1}", typeof(JsonSerializer).Namespace, typeof(JsonSerializer).Assembly.FullName);
			Console.WriteLine();

			try
			{
				TestHarness.Test();
			}
			catch (Exception ex)
			{
				Console.WriteLine("Failed with unhandled exception: ");
				Console.WriteLine(ex);
				throw;
			}
		}
	}
;