2

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 ?

6

2 Answers 2

1

It's not possible to deserialize an object. The Json.NET cannot determine the exact class.

Sign up to request clarification or add additional context in comments.

Comments

1

To fix your problem you should change

   [DataMember]
   public Dictionary<int,object> sub { get; set; }

To :

   [DataMember]
   public Dictionary<int,MyClass2> sub { get; set; }

and

MyClass c = new MyClass() { ID = 1, Text = "Hello", sub = new Dictionary<int, object>() };

To

MyClass c = new MyClass() { ID = 1, Text = "Hello", sub = new Dictionary<int, MyClass2>() };

EDIT

To deserialize your MyClass2, MyClassN... you should use TypeNameHandling.All

MyClass o = JsonConvert.DeserializeObject<MyClass>(File.ReadAllText(file), new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All });

1 Comment

I know that it is the possible way to do it..but in Dictionary<int,object> there can be multiple type of objects added like MyClass2,MyClass3,MyClass4 and so on. That's why i have named it to Dictionary<int,object>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.