【发布时间】: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