I am using Newtonsoft Json.NET library for serialization/deserialization.
I have problem deserializing the object which has property as Dictionary < int,object>. In dictionary - Object can be any type.
Here is what I have done for Test.
[DataContract]
public class MyClass
{
[DataMember(Order = 1)]
public int ID { get; set; }
[DataMember]
public string Text { get; set; }
[DataMember]
public Dictionary<int,object> sub { get; set; }
}
[DataContract]
public class MyClass2
{
[DataMember]
public int ID2 { get; set; }
[DataMember]
public string Text2 { get; set; }
}
On button click in simple WPF App.
MyClass c = new MyClass() { ID = 1, Text = "Hello", sub = new Dictionary<int, object>() };
MyClass2 c2 = new MyClass2() { ID2 = 2, Text2 = "sub1" };
c.sub.Add(1, c2);
MyClass2 c3 = new MyClass2() { ID2 = 3, Text2 = "sub2" };
c.sub.Add(2, c3);
string file = "c:\\newfile.txt";
if (File.Exists(file))
File.Delete(file);
Newtonsoft.Json.JsonSerializer ser = new Newtonsoft.Json.JsonSerializer();
File.WriteAllText(file, JsonConvert.SerializeObject(c));
MyClass o = JsonConvert.DeserializeObject<MyClass>(File.ReadAllText(file));
}
Serilaized Json String -
{"Text":"Hello","sub":{"1":{"ID2":2,"Text2":"sub1"},"2":{"ID2":3,"Text2":"sub2"}},"ID":1}
At Deserialization - MyClass instance's proerties are resolved but property Dictionary (sub) has still json string which is not resolved to MyClass2.
Can anyone please help me ?