How to deserialize JSON in .NET Part 3 – Deserialize the .json file

First we create a string variable containing the .json file name and call the file stream.

string fileName = "weather.json";
using FileStream openStream = File.OpenRead(fileName);

Next call the deserialize method passing the stream as an argument.

WeatherForecast weatherForecast = 
await JsonSerializer.DeserializeAsync<WeatherForecast>(openStream);

Now finally print the resulting objects values.

Console.WriteLine($"Date: {weatherForecast.Date}");
Console.WriteLine($"TemperatureCelsius: {weatherForecast.TemperatureCelsius}");
Console.WriteLine($"Summary: {weatherForecast.Summary}");

As a bonus you can iterate over the resulting string array created during the deserialize actions.

foreach(string fc in weatherForecast.SummaryWords) {

Time to run the program and see your result!

Great work! You should feel proud of yourself!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: