Gennady G
Gennady G

Reputation: 1086

Deserialize Dictionary<string, MyClass> from json, possible without Newtonsoft.Json?

Help me to deserialize the Dictionary object.

By example I have my class

[Serializable]
public class MyClass
{
    /// <summary>
    /// some class variables
    /// </summary>
    public string variable_A;

    public decimal variable_B;

    /// <summary>
    /// constructor for example
    /// </summary>
    public MyClass(string s, decimal d)
    {
        variable_A = s;
        variable_B = d;
    }
}

and I create Dictionary - with string as a key, and MyClass object as a value:

Dictionary<string, MyClass> myDictionary = new Dictionary<string, MyClass>
{
    { "key1", new MyClass("some string value", 5) },
    { "key2", new MyClass("some string value", 3) },
    { "key3", new MyClass("some string value", 10) }
};

Here I serialize this data to trasfer to other place:

        string myObjectJson = new JavaScriptSerializer().Serialize(myDictionary);
        Console.WriteLine(myObjectJson);

But how can I do reverse operation - to deserialize this data back to my Dictionary object?

I tried to use DeserializeObject like this:

    JavaScriptSerializer js = new JavaScriptSerializer();
    Dictionary<string, MyClass> dict = (Dictionary<string, Object>)js.DeserializeObject(myObjectJson);


        //// Also tried this method, but it describes deserialize to Dictionary<string, string>, but I have my object in value, not string
        //// http://stackoverflow.com/questions/4942624/how-to-convert-dictionarystring-object-to-dictionarystring-string-in-c-sha

        //// p.s.: don't want to use third-party dll's, like Json.Net 
        //// http://stackoverflow.com/questions/19023696/deserialize-dictionarystring-t

Upvotes: 3

Views: 778

Answers (1)

Ufuk Hacıoğulları
Ufuk Hacıoğulları

Reputation: 38488

You should use the generic overload:

var dict = new JavaScriptSerializer().Deserialize<Dictionary<string, MyClass>>(myObjectJson);

Also make sure that MyClass type has a default constructor.

Upvotes: 3

Related Questions