How to read a JSON file in C#

Share

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 JSON object) into an actual object is called deserialization.

The opposite operation transforming an object into a text representation like JSON is serialization.

We'll go through the deserialization process in the following steps:

  1. Analyze the JSON object.

  2. Define the corresponding C# model.

  3. Read the JSON file 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 JSON properties. For example, use FirstName and not Firstname.

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 the person.json file.

  • Line 9: We used the JsonSerializer.Deserialize() method to transform the file content stored in the text variable into an instance of the Person class.

  • Lines 11–13: We displayed the values of the person object'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.

ReadJsonFile.cs
read-json-file.csproj
Person.cs
person.json
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}");
}
}

Copyright ©2024 Educative, Inc. All rights reserved