我正在尝试将此字典存储为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对象中的词典消失了,我错过了什么吗?
答案 0 :(得分:3)
您忘记了CategorizedDefinition
上的二传手。您需要这样做,以便Newtonsoft在反序列化时设置属性值。
public Dictionary<string, string> CategorizedDefinition
{
get => _categorizedDefinition;
set => _categorizedDefinition = value; // < --magic here
}
但是,由于您正在为Word
类使用构造函数,因此您可能会忘记在该构造函数内设置_categorizedDefinition。这样的事情会做:
// constructor
public Word(string title, Dictionary<string, string> categorizedDefinition)
{
// ignoring title for now, because it already works.
this._categorizedDefinition = categorizedDefinition;
}
private Dictionary<string, string> _categorizedDefinition
public Dictionary<string, string> CategorizedDefinition
{
get => _categorizedDefinition;
set => _categorizedDefinition = value;
}