Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing a List of Objects that contain a Dictionary

I've seen a lot of examples that seem to indicate that what I'm doing should work, but for whatever reason, it doesn't. I'm trying to deserialize a collection of objects, one of the properties of which is a Dictionary, like so:

class Program
{
    static void Main(string[] args)
    {
        var json = "{\"Collection\":[{\"ID\":\"1243\",\"Dictionary\":[{\"Key\":\"color\", \"Value\":\"red\"},{\"Key\":\"size\",\"Value\":\"large\"}]},{\"ID\":\"1243\",\"Dictionary\":[{\"Key\":\"color\", \"Value\":\"blue\"},{\"Key\":\"size\",\"Value\":\"small\"}]}]}";
        //var json = "[{\"ID\":\"1243\",\"Dictionary\":[{\"Key\":\"color\", \"Value\":\"red\"},{\"Key\":\"size\",\"Value\":\"large\"}]},{\"ID\":\"1243\",\"Dictionary\":[{\"Key\":\"color\", \"Value\":\"blue\"},{\"Key\":\"size\",\"Value\":\"small\"}]}]";
        List<MyObject> myObjects = new JavaScriptSerializer().Deserialize<List<MyObject>>(json);
    }
}

[DataContract]
public class MyObject
{
    [DataMember]
    public string ID { get; set; }

    [DataMember]
    public Dictionary<string, string> Dictionary { get; set; }
}

The first json string encapsulates the whole thing in an object - if I run that one it runs fine but myObjects is just an empty list. If I run the second string (without it being wrapped) I get the following error:

Type 'System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' is not supported for deserialization of an array.

From the research I've done this seems like it should be pretty straight forward - anyone have any ideas as to which JSON format I should be using and what is going wrong? The JSON deserializes just fine if I just do one object instead of an array of objects.

like image 309
Ryan Elkins Avatar asked Sep 13 '12 00:09

Ryan Elkins


1 Answers

Yeah true, the deserializers dont deserialize the dictornary object especailly if you have any complex types and dates. The solution for that is use Newtonsoft.Json use Jobject to deserialize you can take this as an example and try.. In your case you can take this to var or Jobject

    JArray resources=(JArray)JsonConvert.DeserializeObject(objJson);
                     itemStores = resources.Select(resource => new Resource`enter code here`
                     {
                         SpaceUsed = long.Parse(resource["indexDiskMB"].ToString()),
                         ItemId =resource["id"].ToString(),
                         CountItems =Int32.Parse(resource["numItems"].ToString()),
                         ItemType=resource["type"].ToString()

                     }).ToList();
like image 132
Praveen Avatar answered Oct 02 '22 14:10

Praveen