【发布时间】:2019-08-09 18:52:07
【问题描述】:
我正在尝试将此字典存储为 json:
Dictionary<string, Dictionary<string, Word>> _cateList;
//class Word
public Word{
private string _title;
public string Title
{
get
{
return _title;
}
set
{
if (string.IsNullOrEmpty(value)){
throw new Exception();
}
_title = value;
}
}
//key:category, value:definition
private Dictionary<string,string> _categorizedDefinition;
public Dictionary<string, string> CategorizedDefinition
{
get
{
return _categorizedDefinition;
}
}
}
所以基本上每个里面都有 3 个字典。 首先我用一些示例代码用 JsonConvert.Serialize 序列化字典,输出的 json 文件如下所示:
//json code
{
"biology": {
"biology": {
"Title": "Tree",
"CategorizedDefinition": {
"Biology": "A plant"
}
}
}
}
//c# code
Dictionary<string, string> temp = new Dictionary<string, string>()
{ {"Biology", "A plant" } };
Word wd = new Word("Tree", temp);
_cateList.Add("biology", new Dictionary<string, Word>()
{
{"biology", wd }
});
但是当我使用这些代码对 json 进行反序列化时:
_cateList = await DataJsonHandler.LoadFromJsonFile();
//method code
public async static Task<Dictionary<string, Dictionary<string, Word>>> LoadFromJsonFile()
{
Dictionary<string, Dictionary<string, Word>> tempDic;
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("CategorizedWords.json");
using (StreamReader sr = new StreamReader(awaitfile.OpenStreamForReadAsync()))
{
//this lines got the same string in the original json file
string lines = sr.ReadToEnd();
tempDic = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, Word>>>(lines);
}
return tempDic;
}
然后再次序列化,我得到了:
{
"biology": {
"biology": {
"Title": "Tree",
"CategorizedDefinition": null
}
}
}
不知道这里发生了什么导致 Word 对象中的字典消失了,我错过了什么吗?
【问题讨论】:
-
请注意:永远不要
throw new Exception();抛出ArgumentException,而是在您的情况下提供有关参数名称和引发异常原因的信息。为了避免您和您的同事在未来遇到一些挫折。
标签: c# dictionary json.net deserialization json-deserialization