0

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?

4
  • 6
    Standard reply: What have you tried so far? Commented Mar 20, 2014 at 14:57
  • No, no one has; perhaps you should try something first? Commented Mar 20, 2014 at 14:58
  • 2
    Code samples? Attempts? Failures? Commented Mar 20, 2014 at 14:58
  • File.WriteAllText is probably a good place to start: msdn.microsoft.com/en-us/library/ms143375%28v=vs.110%29.aspx Commented Mar 20, 2014 at 14:59

2 Answers 2

22

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.

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

4 Comments

@FedorHajdu No worries, dude.
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.
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
@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.
2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.