How To Deserialize JSON from File C#? Single Item and Collection

In this article, I will demonstrate how to deserialize JSON from a file in C# for both a single item and a collection. I will use the standard .NET namespace ‘using System.Text.Json’. For my examples, I use the next C# class:

public class Car
{
  public string Brand { get; set; }
  public string Model { get; set; }
  public int MaxSpeed { get; set; }
}

 

Deserializing a JSON File for a Single Item

Single Json in the File:
single item json

Deserialization:

using MyTestJsonDeserializeFromFile;
using System.Text.Json;
string carItemJson = File.ReadAllText(@"d:\Temp\CarItem.json");
Car myCar = JsonSerializer.Deserialize<Car>(carItemJson);

 

Result:
singel item deserialization example

Deserializing a JSON File for a Collection

JSON collection in the File:
list json

Deserialization:

using MyTestJsonDeserializeFromFile;
using System.Text.Json;
string carListJson = File.ReadAllText(@"d:\Temp\CarsList.json");
List<Car> myCatList = JsonSerializer.Deserialize<List<Car>>(carListJson);

Result:
deserialize json collection from file

Conclusion

In these examples, we read the contents of the JSON file into a string and then use the JsonSerializer.Deserialize() method to deserialize the JSON string into a Person object. For those who need the Newtonsoft.Json library please use the JsonConvert.DeserializeObject(jsonData); method. You may also be interested to read my article on how to generate C# class from JSON.

My Artifacts Are:

  • Visual Studio 2022
  • Console App .Net 7.0

Leave a Comment