When we want to write a JSON data file, we need to first have some data. We can serialize this data from an existing data source. It should be a class, so we can automatically pull the data and C# will know how to convert it.
public class WeatherData
{
public DateTime Date { get; set; }
public int HighTemperature { get; set; }
public double rain { get; set; }
public WeatherData(DateTime date, int Temp, double rain)
{
this.Date = date;
this.TemperatureFahrenheit = Temp;
this.rain = rain;
}
}
Next we will need to create some data points, and then put it into our sample data set.
WeatherData[] temps = new WeatherData[5];
temps[0] = new WeatherData(new DateTime(2022, 4, 21), 72, 0);
temps[1] = new WeatherData(new DateTime(2022, 4, 22), 79, 0);
temps[2] = new WeatherData(new DateTime(2022, 4, 23), 83, 0);
temps[3] = new WeatherData(new DateTime(2022, 4, 24), 82, .1);
temps[4] = new WeatherData(new DateTime(2022, 4, 25), 80, .5);
Then we will open a file for writing and serialize our data to export it. To do so we will need to use the following libraries:
using System.Text.Json;
using System.Text.Json.Serialization;
using System.IO;
We’ll first start by creating an options variable, and creating a string to write:
var options = new JsonSerializerOptions { WriteIndented = true };
string jsonString = JsonSerializer.Serialize(temps, options);
Console.WriteLine(jsonString);
Once we are sure that our JSON string is correct, we can actually write it to a file.
Luckily, writing text in C# is very easy, you simply use the File command and the WriteAllText method which takes the path to the file, and the contents to write.
File.WriteAllText("Temps.json", jsonString);
Working with JSON Data – Writing to a File was originally found on Access 2 Learn