CSharp · Console
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 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>
{
}
public class MyClass<TValue>
{
public TValue Value { get; set; }
}
class TestClass
{
public static void Test()
{
try
{
Test<int>();
Test<int?>();
Test<uint>();
Test<long>();
Test<ulong>();
Test<byte>();
Test<sbyte>();
Test<short>();
Test<ushort>();
ConsoleAndDebug.WriteLine("\nDone.");
}
catch (Exception ex)
{
ConsoleAndDebug.WriteLine(ex);
throw;
}
}
public static void Test<TValue>()
{
foreach (var json in GetJson())
{
Test<TValue>(json);
}
}
private static void Test<TValue>(string json)
{
ConsoleAndDebug.WriteLine(string.Format("Testing {0}\n", json));
bool jtokenException;
try
{
var settings = new JsonSerializerSettings
{
Converters = { new StrictIntConverter() },
};
Debug.WriteLine("Deserializing indirectly via JToken:");
var token = JToken.Parse(json);
var root = token.ToObject<MyCollection<MyClass<TValue>>>(JsonSerializer.CreateDefault(settings));
Debug.WriteLine("Result:");
Debug.WriteLine(JsonConvert.SerializeObject(root, Formatting.Indented));
Debug.WriteLine("");
jtokenException = false;
}
catch (Exception ex)
{
Debug.WriteLine(ex);
Debug.WriteLine("");
jtokenException = true;
}
bool directException;
try
{
Debug.WriteLine("Deserializing directly:");
var root = JsonConvert.DeserializeObject<MyCollection<MyClass<TValue>>>(json);
Debug.WriteLine("Result:");
Debug.WriteLine(JsonConvert.SerializeObject(root, Formatting.Indented));
Debug.WriteLine("");
directException = false;
}
catch (Exception ex)
{
Debug.WriteLine(ex);
Debug.WriteLine("");
directException = true;
}
Assert.IsTrue(jtokenException == directException);
ConsoleAndDebug.WriteLine(directException ? "Deserialization failed using both methods." : "Deserialization succeeded using both methods.");
}
static IEnumerable<string> GetJson()
{
var json = new[]
{
@"[{""Value"":4.0}]",
@"[{""Value"":4.5}]",
@"[{""Value"":""4.5""}]",
@"[{""Value"":""4.0""}]",
@"[{""Value"":""222222222210101010101010101""}]",
@"[{""Value"":101},{""Value"":4.5},{""Value"":202}]",
};
return json;
}
}
public class StrictIntConverter : StrictIntConverterBase
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(int) || objectType == typeof(int?);
}
}
public abstract class StrictIntConverterBase : JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
Type type = (Nullable.GetUnderlyingType(objectType) ?? objectType);
bool isNullable = (Nullable.GetUnderlyingType(objectType) != null);
if (reader.TokenType == JsonToken.Null)
{
if (isNullable)
return null;
throw new JsonSerializationException(string.Format("Null value for {0}", objectType));
}
else if (reader.TokenType == JsonToken.Float)
{
throw new JsonSerializationException(string.Format("Floating-point value {0} found for {1}.", reader.Value, type));
}
else
{
// Integer or string containing an integer
if (reader.Value.GetType() == type)
return reader.Value;
return JToken.Load(reader).ToObject(type);
}
}
public override bool CanWrite { get { return false; } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
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;
}
}
}