To save data to a JSON file in C#, first, you need to serialize the data into a JSON string, then write that string to a file. C#'s System.Text.Json
library makes it easy to serialize and deserialize JSON data.
Here's an example code that serializes a Dictionary<string, string>
object to a JSON string, then saves the JSON string to a file:
main.cs662 chars25 lines
In this example, the Dictionary<string, string>
object data
is serialized to a JSON string using the JsonSerializer.Serialize()
method. Then, the File.WriteAllText()
method is used to write the JSON string to a file named "data.json". Finally, a message is printed to the console to confirm that the data was saved.
Note that in this example, we're using File.WriteAllText()
to write the entire JSON string to a file. If you have a large JSON object or you want to avoid loading the entire object into memory, you can use a JsonWriter
to write the data to a file as a stream.
gistlibby LogSnag