0

I'm using a json file as a data source in a small app written in C#. I spent last evening looking after the best ways to do CRUD actions with a json data source and the one thing bugging me is that it doesn't seem possible to add/modify data without serializing the whole file to my class, adding an item to the list/updating an item then rewrite the whole thing to the file.

Something like that, which I'd like to avoid if possible :

 var allUsers = jData.ToObject<List<JsonEntry>>();
            allUsers.Add(newEntry);
            var convertedItems = JsonConvert.SerializeObject(allUsers, Formatting.Indented);
            File.WriteAllText("UsersConfiguration.json", convertedItems);

Any idea on how to handle writing/updating in a better way ?

Thanks in advance !

8
  • What data structure are you trying to implement? Is this just a single collection of items? Multiple collections? Do they have relationships? Commented May 3, 2018 at 8:26
  • How do you expect to manipulate the text in the file without re-writing it? AFAIK, that can't be done in plain c#. Commented May 3, 2018 at 8:27
  • If you don't want to serialize to a class then you can follow one of the mentioned approach 1) Use JsonTextReader and JsonTextWriter of NewtonSoft 2) Serialzie to JObject and update the value and deserialize back to Json string to write to file. Commented May 3, 2018 at 8:27
  • @bommelding I couldn't agree more but there are options if the OP's data structure is really simple Commented May 3, 2018 at 8:29
  • 2
    @DanielleSummers simple or not, JSON is a hierarchical data structure persisted as text. Both of these conditions make it highly improbable that one can perform partial serialisation Commented May 3, 2018 at 8:35

1 Answer 1

2

You could engineer something involving json chunks, but it would be hacky. The safest way is to carry on as you are, or maybe consider a NoSQL database since you're up against the "if only this file wasn't really a file" problem :P

Sign up to request clarification or add additional context in comments.

2 Comments

The thing is, I'm using json flat file because I know I won't have a lot of data and it will never happen that 1000 users are going to read/write/update on it at the same time. From what I see on the Net and the answers here I'm doomed to carry on like this.
Haha, doomed is a good word for when a better solution isn't worth the effort. Beware thinking it's only small and not many people use it, I currently maintain a 20year old system used by about 30 people, and if they hire 2 more staff, this thing will race condition and file-lock itself into oblivion :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.