首页 > 解决方案 > JSON.net - C#:反序列化字典时的空引用

问题描述

我在反序列化我之前序列化的字典时遇到问题。

字典正在使用自定义字段 ( <int, DialogueSave>),所以我想知道这不起作用的原因是否是因为 JSON.net 无法将字典反序列化为任何内容,但<string,string>......在这种情况下,我不知道该做什么或如何做去修复那个。

以下是相关代码:

[System.Serializable]
    public class DialogueSave
    {
        public string dialogue;
        public int endActionID;
        // other stuff
    }

    [System.Serializable]
    public class DialogueSaveDictionary
    {
        [SerializeField] public Dictionary<int, DialogueSave> saveDictionary;
    }

    void Save()
    {

    DialogueSaveDictionary saveData = new DialogueSaveDictionary();
    saveData.saveDictionary = new Dictionary<int, DialogueSave>();

    // trying to read Json saved file and deserialize in order to add new 
    // items to dictionary and serizalize again
    string jsonSavedDialoguePath = Application.dataPath + "/dialogueSave.json";
    StreamReader reader = new StreamReader(jsonSavedDialoguePath);

    saveData.saveDictionary = JsonConvert.DeserializeObject<Dictionary<int, DialogueSave>>(reader.ReadToEnd());

    // add new data on top of already saved data
    }

这段代码没有出现错误,但是当我开始通过字典条目将实际的新数据添加到反序列化的保存数据中时,我得到一个NullReferenceException反序列化的 JSON 由于某种原因给了我一个空字典

编辑:这是 json 序列化为的示例

{
  "saveDictionary": {
    "123000": {
      "dialogue": "hey",
      "endActionID": 2
    },
    "123001": {
      "dialogue": "bye",
      "endActionID": 1
    }
}

标签: c#jsonunity3djson.netdeserialization

解决方案


推荐阅读