从json反序列化Dictionary <string,myclass =“”>,没有Newtonsoft.Json?</string,>

时间:2014-04-29 21:53:27

标签: c# json serialization dictionary

帮我反序列化Dictionary对象。

通过示例我有我的班级

[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;
    }
}

我创建了Dictionary - 将字符串作为键,将MyClass对象作为值:

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) }
};

在这里,我将这些数据序列化以转移到其他地方:

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

但是如何进行反向操作 - 将此数据反序列化回我的Dictionary对象?

我试着像这样使用DeserializeObject:

    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

1 个答案:

答案 0 :(得分:3)

您应该使用泛型重载:

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

还要确保MyClass类型具有默认构造函数。