To write to a JSON file in C#, first you need to create a class that matches the structure of your JSON object. This will allow us to serialize the object from the class to the actual JSON format. Here is an example class representing a person object:
main.cs140 chars7 lines
Next, you need to create an instance of your Person object and set its properties.
main.cs91 chars7 lines
After that, use the using
statement to create a new StreamWriter
and serialize the instance of your Person
object to the JSON format using JsonConvert.SerializeObject
method.
main.cs162 chars6 lines
This code will write the serialized JSON to a file named "example.json" in the root directory of the C drive. You can modify the filename and directory to suit your needs.
To read the JSON file back into a C# object, simply swap the JsonConvert.SerializeObject
method with JsonConvert.DeserializeObject
method and specify the Person
type as the second parameter.
main.cs194 chars6 lines
This code will read and deserialize the JSON object stored in the file back to a C# object of type Person
.
gistlibby LogSnag