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:
Deserialization:
using MyTestJsonDeserializeFromFile; using System.Text.Json; string carItemJson = File.ReadAllText(@"d:\Temp\CarItem.json"); Car myCar = JsonSerializer.Deserialize<Car>(carItemJson);
Result:
Deserializing a JSON File for a Collection
JSON collection in the File:
Deserialization:
using MyTestJsonDeserializeFromFile; using System.Text.Json; string carListJson = File.ReadAllText(@"d:\Temp\CarsList.json"); List<Car> myCatList = JsonSerializer.Deserialize<List<Car>>(carListJson);
Result:
Conclusion
In these examples, we read the contents of the JSON file into a string and then use the JsonSerializer.Deserialize
My Artifacts Are:
- Visual Studio 2022
- Console App .Net 7.0