using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Collections.ObjectModel;
using System.Text.Json.Serialization;
public class ProblemDetailsException : System.Exception
public ProblemDetailsException(string message) : base(message) { }
public ProblemDetailsException(string message, Exception inner) : base(message, inner) { }
public ProblemDetailsException(string message, string path) : base(message) => this.Path = path;
public ProblemDetailsException(string message, string path, Exception inner) : base(message, inner) => this.Path = path;
public string Path { get; }
public class DateTimeConverterUsingDateTimeParse : JsonConverter<DateTime>
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
return DateTime.Parse(reader.GetString(),
styles: System.Globalization.DateTimeStyles.RoundtripKind);
var innerEx = new ProblemDetailsException("Invalid DateTime. Please use RoundTripKind (MM-DD-YYYY) - https://docs.microsoft.com/en-us/dotnet/standard/base-types/how-to-round-trip-date-and-time-values");
throw new JsonException(null, innerEx);
public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
writer.WriteStringValue(value.ToString("o"));
[JsonConverter(typeof(DateTimeConverterUsingDateTimeParse))]
public DateTime MyDateTime { get; set; }
public class JsonExtensions
public static T Deserialize<T>(string json, JsonSerializerOptions options = default)
return JsonSerializer.Deserialize<T>(json, options);
catch (JsonException ex) when (ex.InnerException is ProblemDetailsException innerException)
var finalException = new ProblemDetailsException(innerException.Message, ex.Path, ex);
public static void Test()
var ex = Assert.Throws<ProblemDetailsException>(() => InnerTest());
Assert.AreEqual("$.MyDateTime", ex.Path);
Console.WriteLine("Correctly threw exception:\n{0}", ex);
public static void InnerTest()
var json = @"{""MyDateTime"":""junk""}";
var model = JsonExtensions.Deserialize<Model>(json);
public static void Main()
Console.WriteLine("Environment version: {0} ({1})", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , GetNetCoreVersion());
Console.WriteLine("System.Text.Json version: " + 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.Location.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App");
if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2)
return assemblyPath[netCoreAppIndex + 1];