I have the following dictionary that I'd very much like to serialize using Json.Net. The dictionary contains items of the IConvertible
interface allowing me to add whatever primitive type I need to the dictionary.
var dic = new Dictionary<string, IConvertible>();
dic.Add("bool2", false);
dic.Add("int2", 235);
dic.Add("string2", "hellohello");
I have the following implementation for serializing the list using Json.net:
var settings = new JsonSerializerSettings();
settings.TypeNameHandling = TypeNameHandling.Objects;
var dicString = JsonConvert.SerializeObject(dic, Newtonsoft.Json.Formatting.Indented, settings);
This gives me the following output:
{
"$type": "System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.IConvertible, mscorlib]], mscorlib",
"bool2": false,
"int2": 235,
"string2": "hellohello"
}
However. When trying to deserialize as such:
var dic2 = JsonConvert.DeserializeObject<Dictionary<string, IConvertible>>(dicString);
... I get the following error:
Error converting value False to type 'System.IConvertible'. Path 'bool2', line 3, position 16.
I've looked around and found the following; but setting the typeNameHandling didn't solve it. Nor can I decorate the IConvertible
value with a type name attribute seeing as it is a dictionary.
Casting interfaces for deserialization in JSON.NET
I haven't found any other information on the topic so some help would be greatly appreciated!
I also found this solution but it involves creating a ExpandableObjectConverter which isn't a very elegant solution.