4

I am using Web API service. My class is as follows

public class MyClass
{
    public Dictionary<MyClass, List<MyClass>> MyDataDictionary { get; set; }
    public string Id { get; set; }
    public string Name { get; set; }

    public MyClass(string id, string name)
    {
        Id = id;
        Name = name;
    }
}

I am facing problem with serialization of dictionary Key, which is composite type MyClass. When WebAPI returns MyClass instance, I see that dictionary key are not serialised, instead its type (MyNamespace.MyClass) is present there.

MyClassObj.MyDataDictionary.Add(new MyClass("1", "Name1") , List);

Always List is serialized. why not Key Object, how to fix it?

{  
   "Id":2,"Name":"Unknown",

   "MyDataDictionary":{  
      "*MyNamespace.MyClass*":[  
         {  
            "Id":2, "Name":"Th/Abd",
            "MyDataDictionary ":null
         }
      ]
   }
}
Pavan
  • 1,023
  • 2
  • 12
  • 25
  • How do you expect them to be serialized in a JSON or even XML structure? Please provide an example of the result you are expecting after the serialization and show us what you are getting instead. – Federico Dipuma Apr 18 '16 at 10:23
  • 1
    Try this http://stackoverflow.com/a/27043792/6017401 – ChrisS Apr 18 '16 at 10:39
  • As @ChrisS indicates, this is known limitation of Json.NET. See [Not ableTo Serialize Dictionary with Complex key using Json.net](https://stackoverflow.com/questions/24504245). For additional workarounds, see [Usage-specific serialization for complex type in Dictionary with JSON.Net](https://stackoverflow.com/questions/27332723) – dbc Apr 18 '16 at 15:12

0 Answers0