【问题标题】:Deserialize Dictionary<string, MyClass> from json, possible without Newtonsoft.Json?从 json 反序列化 Dictionary<string, MyClass>,可能没有 Newtonsoft.Json?
【发布时间】:2014-04-29 21:53:27
【问题描述】:

帮我反序列化 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

【问题讨论】:

  • 为什么不能使用第三方库?这是一项任务还是您只是想自己学习如何做?
  • 嗨,稀树草原!想学,如果答案很简单。如果没有简单的解决方案,我也会使用第三方。不想使用,因为我不完全了解如果使用外部代码在我的项目中会发生什么..

标签: c# json serialization dictionary


【解决方案1】:

你应该使用泛型重载:

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

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

【讨论】:

  • 是的,非常感谢!这就是答案。管理员,请点赞这个答案(我需要 15 声望,还不能投票)
  • @Rockie 很高兴为您提供帮助。既然你问了这个问题,你仍然可以accept this as the answer
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-15
  • 1970-01-01
  • 2020-05-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多