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.ComponentModel;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
[TypeConverter(typeof(TimeConverter))]
public class Time : IComparable<Time>
public string Value { get; set; }
public int CompareTo (Time other) => Value.CompareTo(other.Value);
public override string ToString() => Value ?? "";
public static Time Parse(string s) => new Time { Value = s };
public class TimeConverter : TypeConverter
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
return sourceType == typeof(string) && base.CanConvertFrom(context, sourceType);
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
return value is string s ? Time.Parse(s) : base.ConvertFrom(context, culture, value);
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
return destinationType == typeof(string) && value is Time t
: base.ConvertTo(context, culture, value, destinationType);
public static void Test()
var time = Time.Parse("7:00AM");
var json = JsonConvert.SerializeObject(time);
var dictionary = new SortedDictionary<Time, string> {
[Time.Parse("7:00AM")] = "aaa",
[Time.Parse("8:00AM")] = "bbb",
[Time.Parse("9:00AM")] = "ccc"
var json2 = JsonConvert.SerializeObject(dictionary, Formatting.Indented);
Console.WriteLine(json2);
var dictionary2 = JsonConvert.DeserializeObject<SortedDictionary<Time, string>>(json2);
Assert.IsTrue(dictionary.Values.SequenceEqual(dictionary2.Values));
Assert.IsTrue(dictionary.Keys.Select(k => k.ToString()).SequenceEqual(dictionary2.Keys.Select(k => k.ToString())));
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.Location.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App");
if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2)
return assemblyPath[netCoreAppIndex + 1];