0

I'm having an issue deserializing a dictionary that i've previously serialized.

The dictionary is using a custom field (<int, DialogueSave>) so I'm wondering if the reason this isn't working is because JSON.net cant deserialize dictionaries into anything but <string,string> ... in which case I have no clue what to do or how I could go fixing THAT.

The following is the relevant code:

[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
    }

No error appears through this code, however when I start to add the actual new data to the deserialized saved data via dictionary entry, I get a NullReferenceException deserializing the JSON is giving me a null dictionary for some reason

edit: this is an example of what the json serializes as

{
  "saveDictionary": {
    "123000": {
      "dialogue": "hey",
      "endActionID": 2
    },
    "123001": {
      "dialogue": "bye",
      "endActionID": 1
    }
}
Kabir
  • 123
  • 8
  • Would you mind to share a Sample Json structure you are using ? – Mr Milk Jan 31 '19 at 18:58
  • @MrMilk I edited in an example of the contents of the serialized json file (if i understood what you're asking correctly) – Kabir Jan 31 '19 at 19:11
  • 2
    Given that JSON, shouldn't you be deserializing `DialogueSaveDictionary` rather than `Dictionary`? – dbc Jan 31 '19 at 20:15
  • 2
    @dbc bingo! Thank you that was it, i wish i could mark you for solving it – Kabir Jan 31 '19 at 20:52

0 Answers0