custom type as dictionary key

Sep 12, 2014 at 8:43 PM
Edited Sep 12, 2014 at 8:50 PM
I have a Dictionary defined like this:
Dictionary<Time, Mark>
The Time class is defined like this:
    public class Time
    {
        public Byte Hour;    // 0...23
        public Byte Minute;  // 0...59

        public Time()
        {
            Hour   = (Byte)0;
            Minute = (Byte)0;
        }

        public Time(Byte hour, Byte minute)
        {
            Hour   = (Byte)( (   hour > 23 ) ? 23 : hour   );
            Minute = (Byte)( ( minute > 59 ) ? 59 : minute );
        }

        public Time(String stringified)
        {
            Hour   = 0;
            Minute = 0;

            String[] parts = stringified.Split(':');

            if ( parts.Length == 2 )
            {
                String hour   = parts[0];
                String minute = parts[1];

                if ( ( hour.Length == 2 ) && ( minute.Length == 2 ) )
                {
                    Byte.TryParse(hour,   out Hour);
                    Byte.TryParse(minute, out Minute);

                    Hour   = (Byte)( (   Hour > 23 ) ? 23 : Hour );
                    Minute = (Byte)( ( Minute > 59 ) ? 59 : Minute );
                }
            }
        }

        public override String ToString()
        {
            return String.Format("{0}{1}:{2}{3}", ((Hour<10)?"0":""), Hour, ((Minute<10)?"0":""), Minute);
        }
    }
When I serialize like so:
String json = JsonConvert.SerializeObject(this, Formatting.Indented);
System.IO.File.WriteAllText("/Users/pgkbb/Desktop/KbB.prefs/Scheduler.json", json);
... i get:
      "Marks": {
        "00:00": 0,
        "06:00": 1,
        "20:00": 0
      }
... which looks good.

But when I deserialize like so:
String json = System.IO.File.ReadAllText("/Users/pgkbb/Desktop/KbB.prefs/Scheduler.json");
State state = JsonConvert.DeserializeObject<State>(json);
... an exception is thrown that says:
Could not convert string '00:00' to dictionary key type 'MyNamespace.Time'. Create a TypeConverter to convert from the string to the key type object.
I've tried standard .NET TypeConverter subclasses and JsonConverter subclasses and still can't get those string keys to deserialize back into Time objects.

Any help would be greatly appreciated.