How to read a JSON file in C#
The .NET platform provides a handy native library to work with JSON since version 3.0: System.Text.Json. Let's see how it can help us read a JSON object from a file and transform it into a standard C# object.
Technically, transforming a text representation of an object (e.g., a
JSONobject) into an actual object is called deserialization.The opposite operation transforming an object into a text representation like
JSONis serialization.
We'll go through the deserialization process in the following steps:
Analyze the
JSONobject.Define the corresponding C# model.
Read the
JSONfile and create the C# object.
Analyze the JSON object
Let's assume that we have a file named person.json in the same folder as the application with the following content:
{"FirstName": "John","LastName": "Doe","JobTitle": "Developer"}
It's a JSON representation of a person with their first name, last name, and job title.
Define the C# model
Now, let's define a C# class that matches the structure of the JSON file:
public class Person{public string FirstName { get; set; }public string LastName { get; set; }public string JobTitle { get; set; }}
Make sure to use the exact case used for the
JSONproperties. For example, useFirstNameand notFirstname.
Read the JSON file and create the C# object
Finally, let's read the file and deserialize it into a Person object. Here is the code that makes it possible:
using System.IO;using System.Text.Json;class ReadJsonFile{static void Main(){string text = File.ReadAllText(@"./person.json");var person = JsonSerializer.Deserialize<Person>(text);Console.WriteLine($"First name: {person.FirstName}");Console.WriteLine($"Last name: {person.LastName}");Console.WriteLine($"Job title: {person.JobTitle}");}}
Explanation
Line 8: We used the
File.ReadAllText()method to read the content of theperson.jsonfile.Line 9: We used the
JsonSerializer.Deserialize()method to transform the file content stored in thetextvariable into an instance of thePersonclass.Lines 11–13: We displayed the values of the
personobject's properties on the console.
Let's put all together in a .NET console project (read-json-file.csproj). Click the "Run" button below to see the code in action.
using System.IO;using System.Text.Json;class ReadJsonFile{static void Main(){string text = File.ReadAllText(@"./person.json");var person = JsonSerializer.Deserialize<Person>(text);Console.WriteLine($"First name: {person.FirstName}");Console.WriteLine($"Last name: {person.LastName}");Console.WriteLine($"Job title: {person.JobTitle}");}}
Free Resources