using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Collections.ObjectModel;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using Debug = System.Console;
class FooConverter : JsonConverter<Foo>
public override Foo ReadJson(JsonReader reader, Type objectType, Foo existingValue, bool hasExistingValue, JsonSerializer serializer)
Debug.WriteLine((reader as IJsonLineInfo).FormatMessage("Entering ReadJson. ", reader.Path));
var obj = JObject.Load(reader, new JsonLoadSettings { LineInfoHandling = LineInfoHandling.Load });
var theAnswerToken = obj["answer"];
var theAnswer = theAnswerToken.Value<int>();
throw new WrongAnswerException(theAnswerToken as IJsonLineInfo, "Wrong Answer");
Debug.WriteLine((reader as IJsonLineInfo).FormatMessage("Exiting ReadJson. ", reader.Path));
return new Foo { answer = theAnswer };
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, Foo value, JsonSerializer serializer) => throw new NotImplementedException();
public class WrongAnswerException : ApplicationException
public WrongAnswerException() : base() { }
public WrongAnswerException(IJsonLineInfo info, string message, string path = null) : base(info.FormatMessage(message, path)) { }
public static class JsonExtensions
public static string FormatMessage(this IJsonLineInfo lineInfo, string message, string path = null)
if (!message.EndsWith(Environment.NewLine, StringComparison.Ordinal))
message = message.Trim();
if (!message.EndsWith('.'))
message += string.Format(CultureInfo.InvariantCulture, "Path '{0}', ", path);
if (lineInfo != null && lineInfo.HasLineInfo())
message += string.Format(CultureInfo.InvariantCulture, "line {0}, position {1}", lineInfo.LineNumber, lineInfo.LinePosition);
public static void Test()
var wrongAnswer = JsonConvert.SerializeObject(new Foo { answer = -100 }, Formatting.Indented);
Console.WriteLine(wrongAnswer);
Assert.Throws(typeof(WrongAnswerException), () => JsonConvert.DeserializeObject<Foo>(wrongAnswer, new FooConverter()));
var answer = JsonConvert.DeserializeObject<Foo>(wrongAnswer, new FooConverter());
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("Failed with unhandled exception: ");
public static string GetNetCoreVersion()
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];