3

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
Gennady G
  • 996
  • 2
  • 11
  • 28
  • Why can't you use third-party libraries? Is this an assignment or do you just want to learn how to do it yourself? – eddie_cat Apr 29 '14 at 21:58
  • 1
    Hi Savanna! Want to learn, if the answer is simple. If there is no simple solution, I'll use and third-party too. Don't want to use, becouse I don't understand completely what happens in my project if use external code.. – Gennady G Apr 29 '14 at 22:07

1 Answers1

3

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.

Ufuk Hacıoğulları
  • 37,978
  • 12
  • 114
  • 156
  • Yes, thank You very much! This is the answer. Administrators, please upvote this like answer(I need 15 reputation and cannot vote yet) – Gennady G Apr 30 '14 at 08:01
  • @Rockie Glad to help. You can still [accept this as the answer](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) since you asked the question. – Ufuk Hacıoğulları Apr 30 '14 at 08:05