【问题标题】:JsonConvert.DeserializeObject() cannot deserialize the string properlyJsonConvert.DeserializeObject() 无法正确反序列化字符串
【发布时间】: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


【解决方案1】:

您忘记了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;
}

【讨论】:

  • 感谢您的回答!只需在 CategorizedDefinition 上添加 setter 即可解决问题
猜你喜欢
  • 2018-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-06
  • 2021-02-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多