[Fork] //https://stackoverflow.com/questions/63066921/json-deserialization-handle

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 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/63066921/json-deserialization-handle

	public class ArrayItemFilteringListConverter : JsonConverter
	{
		static readonly IContractResolver defaultResolver = JsonSerializer.CreateDefault().ContractResolver;
		readonly IContractResolver resolver;

		public ArrayItemFilteringListConverter() : this(null) { }

		public ArrayItemFilteringListConverter(IContractResolver resolver) => this.resolver = resolver ?? defaultResolver;

        public override bool CanConvert(Type objectType) => CanConvert(resolver, objectType, out _);
	
        static bool CanConvert(IContractResolver resolver, Type objectType, out Type itemType)
        {
			if (objectType.IsArray || objectType.IsPrimitive || objectType == typeof(string) || !typeof(IList).IsAssignableFrom(objectType))
			{
				itemType = null;
				return false;
			}
			itemType = objectType.GetListItemType();
			if (itemType == null)
				return false;
			if (resolver.ResolveContract(itemType) is JsonArrayContract)
				return false;
			return true;
        }
		
		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			if (!CanConvert(serializer.ContractResolver, objectType, out var itemType))
				throw new JsonException(string.Format("Invalid collection type {0}", objectType));
			var contract = serializer.ContractResolver.ResolveContract(objectType);

			if (reader.MoveToContentAndAssert().TokenType == JsonToken.Null)
				return null;
			else if (reader.TokenType != JsonToken.StartArray)
				throw new JsonSerializationException(string.Format("Invalid start token {0}", reader.TokenType));
			
			var list = existingValue as IList ?? (IList)contract.DefaultCreator();
			
            while (reader.Read())
            {
                switch (reader.TokenType)
                {
                    case JsonToken.EndArray:
						return list;
					case JsonToken.StartArray:
					case JsonToken.Comment:
						reader.Skip();
						break;
                    default:
						// Here we take advantage of the fact that List<T> implements the non-generic IList interface.
						list.Add(serializer.Deserialize(reader, itemType));
                        break;
                }
            }
            // Should not come here.
            throw new JsonSerializationException("Unclosed array at path: " + reader.Path);		
		}	

		public override bool CanWrite => false;
		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotImplementedException();
	}
	
    public static partial class JsonExtensions
    {
        public static JsonReader MoveToContentAndAssert(this JsonReader reader)
        {
            if (reader == null)
                throw new ArgumentNullException();
            if (reader.TokenType == JsonToken.None)       // Skip past beginning of stream.
                reader.ReadAndAssert();
            while (reader.TokenType == JsonToken.Comment) // Skip past comments.
                reader.ReadAndAssert();
            return reader;
        }

        public static JsonReader ReadAndAssert(this JsonReader reader)
        {
            if (reader == null)
                throw new ArgumentNullException();
            if (!reader.Read())
                throw new JsonReaderException("Unexpected end of JSON stream.");
            return reader;
        }
		
        public static Type GetListItemType(this Type type)
        {
            while (type != null)
            {
                if (type.IsGenericType)
                {
                    var genType = type.GetGenericTypeDefinition();
                    if (genType == typeof(List<>))
                        return type.GetGenericArguments()[0];
                }
                type = type.BaseType;
            }
            return null;
        }
    }

// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse); 
    public class PropertyValue    
	{
        public string value1 { get; set; } 
        public string value2 { get; set; } 
        public string value3 { get; set; } 
    }

    public class Root    
	{
		[JsonConverter(typeof(ArrayItemFilteringListConverter))]
        public List<PropertyValue> propertyName { get; } = new List<PropertyValue>(); 
	}

    class TestClass
    {
        public static void Test()
        {
			foreach (var json in GetJson())
			{
				Console.WriteLine("\nDeserializing JSON:");
				Console.WriteLine(json);
				
				var root = JsonConvert.DeserializeObject<Root>(json);
				
				var json2 = JsonConvert.SerializeObject(root, Formatting.Indented);
				
				Console.WriteLine("Re-serialized {0}", root);
				Console.WriteLine(json2);
			}
		}	
		
		static IEnumerable<string> GetJson()
		{
			return new [] {
				@"{""propertyName"": [
   {
      ""value1"": ""value"",
      ""value2"": ""value"",
      ""value3"": ""value"" 
   }
]
}",
				@"{""propertyName"": [
     [] 
]
}",
				@"{""propertyName"": /* Comment */ [ /* COmment */
   {
      ""value1"": ""value"",
      ""value2"": ""value"",
      ""value3"": ""value"" 
   },
   /* Comment */ {} /* COmment */, /* Comment */ null /* Comment */,
   /* Comment */ [],   
   {
      ""value1"": ""value"",
      ""value2"": ""value"",
      ""value3"": ""value"" 
   }
]
}"
				
			};
		}
	}

	public class Program
	{
		public static void Main()
		{
			Console.WriteLine("Environment version: {0} ({1})", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , GetNetCoreVersion());
			Console.WriteLine("{0} version: {1}", typeof(JsonSerializer).Assembly.GetName().Name,  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.CodeBase.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;
		}
	}
;