2

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 ?

techno
  • 6,100
  • 16
  • 86
  • 192
  • Does this answer your question? [json add new object to existing json file C#](https://stackoverflow.com/questions/33081102/json-add-new-object-to-existing-json-file-c-sharp) – Drag and Drop Oct 31 '19 at 10:52

1 Answers1

6

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Hi Jon,Thanks for your answer.I cannot use separate files.I'm trying to save the dictionary to a file,so that i can load and use it again.Is there any other better approach. – techno Oct 31 '19 at 10:54
  • 1
    @techno: Better than "load the existing file, merge it in memory then save a new file"? That's going to be the simplest approach. What concern do you have with that? – Jon Skeet Oct 31 '19 at 10:56