Deamination of the list of objects containing the dictionary

I have seen many examples that seem to indicate that what I am doing should work, but for some reason this is not the case. I am trying to deserialize a collection of objects, one of the properties of which is a dictionary, for example:

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 line encapsulates the whole thing in an object - if I run it, then it works fine, but myObjects is just an empty list. If I run the second line (without wrapping it), I get the following error:

Enter '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 deserializing the array.

, , , : - , JSON , ? JSON , .

+5
3

, , , - . Newtonsoft.Json Jobject , . var 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();
+3

, Dictionary<string, string> , . List<KeyValuePair<string, string>> , .

, , - , JSON , . , JSON , - :

// Inside of MyObject class
[DataMember]
public Kvp<string, string>[] Dictionary { get; set; }

public Dictionary<string, string> GetDictionary()
{
    return Dictionary.ToDictionary(x => x.Key, x => x.Value);
}

//////////////////

public class Kvp<T1, T2>
{
    public T1 Key { get; set; }
    public T2 Value { get; set; }
}

Dictionary<string, string> myDictionary = myObjects[0].GetDictionary();

, , .

+1

Obviously, a little late for the part for OP :), but today I hit in the same way and used the following to solve it:

        //var json = "[{'firstName':'John', 'lastName':'Doe'},{'firstName':'Anna', 'lastName':'Smith'},{'firstName':'Peter','lastName': 'Jones'} ]";
        //var json = "{ 'glossary': { 'title': 'example glossary','GlossDiv': { 'title': 'S','GlossList': { 'GlossEntry': { 'ID': 'SGML','SortAs': 'SGML','GlossTerm': 'Standard Generalized Markup Language','Acronym': 'SGML','Abbrev': 'ISO 8879:1986','GlossDef': { 'para': 'A meta-markup language, used to create markup languages such as DocBook.','GlossSeeAlso': ['GML', 'XML'] },'GlossSee': 'markup' } } } } }";
        var json = "{ 'A': 'A0' , 'B' : { 'B2' : 'B2 - Val', 'B3' : [{'B30' : 'B30 - Val1' ,'B31' : 'B31 - Val1'}]}, 'C': ['C0', 'C1']}";
        var jss = new JavaScriptSerializer();

        try
        {
            // Deal with an Object root
            var dict = jss.Deserialize<Dictionary<string, object>>(json);
            //<do stuff>
        }
        catch (InvalidOperationException ioX)
        {
            // Deal with an Array Root
            var dictionaries = jss.Deserialize<Dictionary<string, object>[]>(json);
            foreach (var dict in dictionaries)
            {
                //<do stuff for each dictionary>
            }
        }
+1
source

All Articles