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:
Analyze the JSON
object.
Define the corresponding C# model.
Read the JSON
file and create the C# object.
JSON
objectLet'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.
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, useFirstName
and notFirstname
.
JSON
file and create the C# objectFinally, 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}");}}
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.
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