I want to be able to add users to a Users json file. I'm using Json.net to do this, anyone got any ideas of how I might go about doing this?
2 Answers
Here is a simple way of writing a JSON file in c#
UserData user = Call Method Here
string json = JsonConvert.SerializeObject(user, Formatting.Indented);
File.WriteAllText(@"c:\user.json", json);
This will write a simple JSON file and save it to your computer.
4 Comments
snowYetis
@FedorHajdu No worries, dude.
Paddy1990
hi thanks for the response. this worked fine but it overwrites the existing json file, how do I add one to my existing file? The way I have tried is to deserialise the array of users into a variable list<users>. I then add the new user (hard coded at this moment in time). then serialise it but can't get it to work because I can't implicitly convert type string into Model users. I can upload code if it will help.
Paddy1990
Figured this out I just needed to serialise to a string and write that to the json file, I was creating a new instance of my user model and trying to serialise to that for some reason, moment of stupidity thanks for the help
snowYetis
@user2746139 Sorry about that. I did not see your comments until now. Let me know if you need anymroe help. I am glad you got it to work.
Assuming that you have to add users to an existing JSON file, the basic approach is:
- Read / parse JSON file to get an in-memory data structure
- Modify the data structure to add the users
- Unparse / write the data structure to a new copy of the file.
There is no way to do update-in-place on a JSON file.
File.WriteAllTextis probably a good place to start: msdn.microsoft.com/en-us/library/ms143375%28v=vs.110%29.aspx