write to a json file in csharp

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.cs
public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}
140 chars
7 lines

Next, you need to create an instance of your Person object and set its properties.

main.cs
Person person = new Person
{
    FirstName = "John",
    LastName = "Doe",
    Age = 42
};
91 chars
7 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.cs
using (StreamWriter file = File.CreateText(@"C:\example.json"))
{
    JsonSerializer serializer = new JsonSerializer();
    serializer.Serialize(file, person);
}
162 chars
6 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.cs
using (StreamReader file = File.OpenText(@"C:\example.json"))
{
    JsonSerializer serializer = new JsonSerializer();
    Person person = (Person)serializer.Deserialize(file, typeof(Person));
}
194 chars
6 lines

This code will read and deserialize the JSON object stored in the file back to a C# object of type Person.

gistlibby LogSnag