Create the class skeleton
using Newtonsoft.Json; // Requires installation
public class LINQTutorial
{
private List<Student> _students;
// you may not need this
public static void Main()
{
}
public LINQTutorial()
{
PopulateStudentsData();
}
public List<Student> GetStudents()
{
return _students;
}
void PopulateStudentsData()
{
/* TODO */
}
}
Then read file (students.json) content and converting into C# model.
void PopulateStudentsData()
{
// Get the directory (mine is in \RiderProjects\LearnCSharp\bin\Debug\net8.0\students.json)
string currentDirectory = AppDomain.CurrentDomain.BaseDirectory;
// Join with the file relative path
string filePath = Path.Combine(currentDirectory, "students.json");
// Read JSON file
string json = File.ReadAllText(filePath);
// Deserialize to list of Student objects and assign to _students
_students = JsonConvert.DeserializeObject<List<Student>>(json);
}
To parse (Deserialize) JSON to C# you need to install and import Newtonsoft.Json package.
a) You can do this either by pressing CTRL + . when you're over the JsonConvert
.
b) Or opening the Nuget Package manager, searching for Newtonsoft dependency and installing it in the project
To test it, create an instance of the LINQTutorial
class and call the GetStudents()
method.
var LT = new LINQTutorial();
var students = LT.GetStudents();
For demonstration purposes I'll run a quick LINQ:
var LT = new LINQTutorial();
var students = LT.GetStudents();
var firstStudent = students.First();
Console.WriteLine($"Name: {firstStudent.Name}, Age: {firstStudent.Age}, Country: {firstStudent.Country}");
// Name: Mirza, Age: 18, Country: Bosnia
And that's it!