I have a property that is actually a Dictionary. And I keep many types in this dictionary like TimeSpans, DateTimes, etc. But serializing and deserializing TimeSpans are wrong and it deserializes as string.
var dict = new Dictionary<string, object>();
dict.Add("int", 15);
dict.Add("string", "foo");
dict.Add("timeSpan", new TimeSpan(1,1,1));
dict.Add("dateTime", DateTime.Now);
var settings = new JsonSerializerSettings{
TypeNameHandling = TypeNameHandling.All,
TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple
};
var serializedObj = JsonConvert.SerializeObject(dict, Newtonsoft.Json.Formatting.Indented, settings);
var deserializedObj = (Dictionary<string, object>)JsonConvert.DeserializeObject(serializedObj, settings);
//Displaying the types with LinqPad:
deserializedObj["int"].GetType().Dump();
deserializedObj["string"].GetType().Dump();
deserializedObj["timeSpan"].GetType().Dump();
deserializedObj["dateTime"].GetType().Dump();
RESULTS:
So TimeSpan in an object can't deserialize to a timespan. I've tried with latest version of Json.Net too. But the result is same.
How can I specify type name for TimeSpan? Or should I write a custom converter and how?
Edit:
I did some tests and I changed serialized timeSpan property like this:
""timeSpan"": {
""$type"": ""System.TimeSpan"",
""$value"": ""01:01:01""}
and this time json.net could desrialize it as TimeSpan. But How can I specify $type and $value of TimeSpan at Serialization level like this?