简体   繁体   中英

How to write to a JSON file using C#?

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM