questions/45772447/how-to-let-deserialization-throw-exception-on-non-integer-where-expecting-an-int

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.Collections.ObjectModel;
using System.Diagnostics;
using System.Runtime.Serialization;

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

// https://stackoverflow.com/questions/45772447/how-to-let-deserialization-throw-exception-on-non-integer-where-expecting-an-int#45772447

    public class MyCollection<T> : Collection<T>
    {
        [OnError]
        void OnError(StreamingContext context, ErrorContext errorContext)
        {
            if (errorContext.OriginalObject != this)
            {
                // Error occurred deserializing an item in the collection.  Swallow it.
                errorContext.Handled = true;
            }
        }
    }

    public class MyClass<TValue>
    {
        public TValue Value { get; set; }
    }


    class TestClass
    {
        public static void Test()
        {
            try
            {
                Test<int>();
                ConsoleAndDebug.WriteLine("\nDone.");
            }
            catch (Exception ex)
            {
                ConsoleAndDebug.WriteLine(ex);
                throw;
            }
        }

        public static void Test<TValue>()
        {
            foreach (var json in GetJson())
            {
                Test<TValue>(json.Item1, json.Item2);
            }
        }

        private static void Test<TValue>(string json, int expectedCount)
        {
            ConsoleAndDebug.WriteLine(string.Format("Testing {0}", json));

            var root = JsonConvert.DeserializeObject<MyCollection<MyClass<TValue>>>(json);

            ConsoleAndDebug.WriteLine(string.Format("Count = {0}, Expected Count = {1}.\n", root.Count, expectedCount));

            Assert.IsTrue(root.Count == expectedCount);
        }

        static IEnumerable<Tuple<string, int>> GetJson()
        {
            var json = new[] 
                {
                    Tuple.Create(@"[{""Value"":101},{""Value"":4.5},{""Value"":202}]", 2),
                    Tuple.Create(@"[{""Value"":4.0}]", 0),
                    Tuple.Create(@"[{""Value"":4.5}]",0),
                    Tuple.Create(@"[{""Value"":""4.5""}]", 0),
                    Tuple.Create(@"[{""Value"":""4.0""}]", 0),
                    Tuple.Create(@"[{""Value"":""222222222210101010101010101""}]", 0),
                };
            return json;
        }
    }

    public class AssertionFailedException : System.Exception
    {
        public AssertionFailedException() : base() { }

        public AssertionFailedException(string s) : base(s) { }
    }

    public static class Assert
    {
        public static void IsTrue(bool value)
        {
            IsTrue(value, "failed");
        }

        public static void IsTrue(bool value, string message)
        {
            if (value == false)
                throw new AssertionFailedException(message ?? "failed");
        }
    }

    public static class ConsoleAndDebug
    {
        public static void Write(object s)
        {
            Console.Write(s);
            Debug.Write(s);
        }

        public static void WriteLine(object s)
        {
            Console.WriteLine(s);
            Debug.WriteLine(s);
        }
    }
	public class Program
	{
		public static void Main()
		{
			Console.WriteLine("Environment version: " + Environment.Version);
			Console.WriteLine("Json.NET version: " + typeof(JsonSerializer).Assembly.FullName);
			Console.WriteLine();

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