Search code examples
c#.netdictionaryjsonconvert

Saving and Loading Dictionary from File


I'm trying to save a dictionary to a file and load the contents of the same to a Dictionary Object.I'm appending the dictionary to a file using the following code

string json = JsonConvert.SerializeObject(dict);
File.AppendAllText("config.fcj", json);

But while loading i keep getting the following error.

Additional text encountered after finished reading JSON content: {. Path '', line 1, position 375.

Do i need to add a New Line after each save ?


Solution

  • You can't append one JSON document to another and expect to end up with a valid JSON file as a result. JSON parsers (reasonably) expect a single document per file.

    Instead, load the original JSON file (presumably as a dictionary), merge it with the new content, and then save it again, replacing the original file.

    Alternatively, use a separate file each time, and write code to load all the files and then merge the content in memory.