When we develop software applications, we use JSON (JavaScript Object Notation) as a data interchange format, therefore we need to understand how to read and parse JSON files.

In this article, we are going to explore six distinct ways to read and parse a JSON file in C#, providing examples to illustrate how to use them effectively. We will parse the JSON string using either the Newtonsoft.Json library or the System.Text.Json namespace in each method, featuring a unique combination of reading and parsing tools.


VIDEO: How to Read and Parse a JSON File in C# video.


At the end of the article, we will compare the performance of these methods using the BenchmarkDotNet library.

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!
To download the source code for this article, you can visit our GitHub repository.

Let’s dive in.

Prepare the Environment

Before we start discussing the various methods we can use to read and parse JSON files in .NET, we need to define a sample JSON file and populate it with data:

[
    {
        "teacherId":1,
        "firstName":"Clare",
        "lastName":"Anyanwu",
        "birthYear":1987,
        "level":8,
        "courses":
        [
            {
                "name":"Biology",
                "creditUnits":3,
                "numberOfStudents":42
            },
            {
                "name":"Basic Science",
                "creditUnits":4,
                "numberOfStudents":35
            }
        ]
    }
]

This JSON file will be the input data for all the methods in this article.

Read and Parse JSON File Using Newtonsoft.Json

Newtonsoft.Json or JSON.NET is a popular, open-source library for reading and parsing JSON data in .NET. In this section, let’s look at some of the different ways we can work with the JSON.NET library to read and parse a JSON file in C#.

Read and Parse a JSON File Into a .NET Object With Newtonsoft.Json

To read and parse a JSON file into a .NET object with Newtonsoft.Json, we can use the JsonConvert.DeserializeObject() method, which is a part of the Newtonsoft.Json library.

First, we define the Teacher class:

public class Teacher
{
    public int TeacherId { get; set; }
    public string FirstName { get; set; } = string.Empty;
    public string LastName { get; set; } = string.Empty;
    public int BirthYear { get; set; }
    public int Level { get; set; }
    public List<Course> Courses { get; set; }
}

This class contains properties that correspond to the data in the JSON file. The Courses property is a list of the type Course:

public class Course
{
    public string Name { get; set; } = string.Empty;
    public int CreditUnits { get; set; }
    public int NumberOfStudents { get; set; }
}

Now, let’s create a ReadAndParseJsonFileWithNewtonsoftJson class and a _sampleJsonFilePath variable:

public class ReadAndParseJsonFileWithNewtonsoftJson
{
    private readonly string _sampleJsonFilePath;

    public ReadAndParseJsonFileWithNewtonsoftJson(string sampleJsonFilePath)
    {
        _sampleJsonFilePath = sampleJsonFilePath;
    }
}

Here, we define a class that will contain all our methods that will use the Newtonsoft.Json library to parse our JSON data. We also define a private readonly string that points to our sample JSON file path.

Then, we define a constructor that initializes _sampleJsonFilePath with the value of the sampleJsonFilePath parameter. Classes that call our JSON file reading and parsing methods will set the value of this parameter.

Now, let’s define a UseUserDefinedObjectWithNewtonsoftJson() method:

public List<Teacher> UseUserDefinedObjectWithNewtonsoftJson()
{
    using StreamReader reader = new(_sampleJsonFilePath);
    var json = reader.ReadToEnd();
    List<Teacher> teachers = JsonConvert.DeserializeObject<List<Teacher>>(json);

    return teachers;
}

Here,  we create a new StreamReader object by passing the path of our JSON file to the constructor. The using statement ensures that the StreamReader is disposed of properly when we’re done with it.

After that, we call the JsonConvert.DeserializeObject() method, passing in the JSON string and the Teacher class as the generic type parameter.

Finally, we return a list of Teacher objects deserialized from the JSON data.

We can see that using the StreamReader class and the Newtonsoft.Json library to read and parse JSON data into .NET objects is quite simple.

Read and Parse a JSON File Using JsonTextReader in Newtonsoft.Json

Now, let’s see how we can read and parse a JSON file using the JsonTextReader with the Newtonsoft.Json library in C#.

First, let’s define a UseJsonTextReaderWithNewtonsoftJson() method:

public List<Teacher> UseJsonTextReaderInNewtonsoftJson()
{
    var serializer = new JsonSerializer();
    List<Teacher> teachers = new();
    using (var streamReader = new StreamReader(_sampleJsonFilePath))
    using (var textReader = new JsonTextReader(streamReader))
    {
        teachers = serializer.Deserialize<List<Teacher>>(textReader);
    }

    return teachers;
}

Here, we create a JsonSerializer object to deserialize the JSON data. Then, we also create an empty List of type Teacher to store the deserialized data.

Next, we define a StreamReader object to read the contents of the JSON file, and then use a JsonTextReader to read the JSON data from the stream reader.

Finally, we call the Deserialize() method of the JsonSerializer object, passing in the JsonTextReader. We invoke this method to convert the JSON data into a List of Teacher objects and return the list.

Read and Parse JSON File Using JArray.Parse() in Newtonsoft.Json

Let’s see how we can use the JArray.Parse() method in Newtonsoft.Json to read and parse a JSON file. To demonstrate this, let’s define a UseJArrayParseWithNewtonsoftJson() method:

public List<Teacher> UseJArrayParseInNewtonsoftJson()
{
    using StreamReader reader = new(_sampleJsonFilePath);
    var json = reader.ReadToEnd();
    var jarray = JArray.Parse(json);
    List<Teacher> teachers = new();

    foreach (var item in jarray)
    {
        Teacher teacher = item.ToObject<Teacher>();
        teachers.Add(teacher);
    }

    return teachers;
}

First, we use a StreamReader object to read the contents of the JSON file into a string variable called json.

Next, we invoke the JArray.Parse() method and pass the JSON string to it. This method parses the string into a JArray object, which is a collection of JToken objects representing the data in the JSON file.

We then create an empty list of Teacher objects called teachers.

We use a foreach loop to iterate through each JToken in the JArray. For each JToken, we call the ToObject<Teacher>() method to create a Teacher object using the properties of the JToken.

After that, we add the newly created Teacher object to the teachers list.

Finally, we return the list of teachers.

Read and Parse JSON File Using System.Text.Json

In this section, let’s discuss various methods that we can use to read and parse a JSON file in C# using the native System.Text.Json namespace.

First, let’s define a ReadAndParseJsonFileWithSystemTextJson class and a _sampleJsonFilePath variable:

public class ReadAndParseJsonFileWithSystemTextJson
{
    private readonly string _sampleJsonFilePath;

    public ReadAndParseJsonFileWithSystemTextJson(string sampleJsonFilePath)
    {
        _sampleJsonFilePath = sampleJsonFilePath;
    }
}

Unlike the Newtonsoft.Json library, the System.Text.Json library does not have case-insensitive property name matching built-in. As a result, we need to include a mechanism to enable this functionality.

To allow for case-insensitive property name matching during JSON deserialization, let’s define an instance of the JsonSerializerOptions class:

private readonly JsonSerializerOptions _options = new()
{
    PropertyNameCaseInsensitive = true
};

When we pass the _options parameter to the JsonSerializer.Deserialize() method, the deserializer will be able to match properties regardless of their casing.

This can be useful in scenarios where our JSON file may come from different sources with different casing conventions.

Now, let’s explore the various methods for reading and parsing a JSON file.

Read and Parse JSON File Using File.ReadAllText() With System.Text.Json

First, let’s learn how to read and parse a JSON file using the File.ReadAllText() method in conjunction with the System.Text.Json library.

Let’s take a look at the UseFileReadAllTextWithSystemTextJson() method:

public List<Teacher> UseFileReadAllTextWithSystemTextJson()
{
    var json = File.ReadAllText(_sampleJsonFilePath);
    List<Teacher> teachers = JsonSerializer.Deserialize<List<Teacher>>(json, _options);

    return teachers;
}

Here, we use the File.ReadAllText() method to read the contents of the specified file into a string variable called json. This method returns the entire contents of the file as a single string.

Next, we use the JsonSerializer class to deserialize the json string into a list of Teacher objects. We do this by invoking the JsonSerializer.Deserialize<List<Teacher>>() method, which takes in the JSON string and a type argument (in this case, List<Teacher>) and we return an object of that type.

Finally, we return the deserialized list of Teacher objects.

As we can see, using the File.ReadAllText() method in combination with the JsonSerializer class allows us to quickly and easily convert JSON data into strongly-typed objects.

Read and Parse JSON File Using File.OpenRead() With System.Text.Json

Alternatively, we can use the File.OpenRead() method with System.Text.Json to read and parse JSON files in our C# applications.

To start, let’s define a  UseFileOpenReadTextWithSystemTextJson() method:

public List<Teacher> UseFileOpenReadTextWithSystemTextJson()
{
    using FileStream json = File.OpenRead(_sampleJsonFilePath);
    List<Teacher> teachers = JsonSerializer.Deserialize<List<Teacher>>(json, _options);

    return teachers;
}

Here, we create a new FileStream object by calling File.OpenRead() and pass it the path of our JSON file. This method opens the file in read-only mode and returns an object, that we store in a variable named json.

We then call the static method JsonSerializer.Deserialize() to convert the FileStream object into a list of Teacher instances.

Finally, we return the list of teachers.

Read and Parse JSON File Using StreamReader With System.Text.Json

We can also use the StreamReader class to read a JSON file, and then use the System.Text.Json library to parse the returned JSON string.

To see how this works, let’s create a UseStreamReaderWithSystemTextJson() method:

public List<Teacher> UseStreamReaderWithSystemTextJson()
{
    using StreamReader streamReader = new(_sampleJsonFilePath);
    var json = streamReader.ReadToEnd();
    List<Teacher> teachers = JsonSerializer.Deserialize<List<Teacher>>(json, _options);

    return teachers;
}

In this method, we create a new instance of StreamReader and pass it the path of our JSON file.

We then call the ReadToEnd() method of the StreamReader object to read the entire contents of the JSON file as a string, which we store in a variable called json.

Next, we invoke the static method JsonSerializer.Deserialize() to convert the JSON data in the string into a list of Teacher objects.

Finally, we return the list of teachers.

Benchmark All Methods

Now that all our methods are ready, let’s compare their time and memory performance using the BenchmarkDotNet library.

To see the benchmark implementation, you can look at this file in our repository.

Now, let’s run our benchmark tests and inspect the results on the console:

|                                 Method |      Mean |     Error |    StdDev |    Median | Allocated |
|--------------------------------------- |----------:|----------:|----------:|----------:|----------:|
|  UseFileOpenReadTextWithSystemTextJson |  90.94 ms |  2.632 ms |  7.762 ms |  94.99 ms |   4.22 MB |
|      UseStreamReaderWithSystemTextJson | 120.05 ms |  3.551 ms | 10.470 ms | 125.52 ms |   23.1 MB |
|   UseFileReadAllTextWithSystemTextJson | 120.70 ms |  3.407 ms | 10.047 ms | 125.36 ms |  23.09 MB |
|      UseJsonTextReaderInNewtonsoftJson | 179.27 ms |  6.153 ms | 18.047 ms | 185.46 ms |   5.14 MB |
| UseUserDefinedObjectWithNewtonsoftJson | 182.26 ms |  5.289 ms | 15.593 ms | 189.16 ms |  20.25 MB |
|         UseJArrayParseInNewtonsoftJson | 709.25 ms | 19.144 ms | 56.447 ms | 729.78 ms |  77.72 MB |

Based on the benchmark test results, the fastest method to read and parse a JSON file in C# is the UseFileOpenReadTextWithSystemTextJson() method, with an average time of 90.94 ms. This method also utilizes the least amount of memory among all the tested methods, with 4.22 MB allocated.

As we can see, UseStreamReaderWithSystemTextJson() and UseFileReadAllTextWithSystemTextJson() methods are slightly slower than the UseFileOpenReadTextWithSystemTextJson() method, with average times of 120.05 ms and 120.70 ms, respectively. However, they allocate significantly more memory, with 23.1 MB and 23.09 MB allocated, respectively.

Also, the UseJsonTextReaderInNewtonsoftJson() method and the UseUserDefinedObjectWithNewtonsoftJson() method are both slower than the System.Text.Json-based methods, with average times of 179.27 ms and 182.26 ms, respectively. However, the UseJsonTextReaderInNewtonsoftJson() method consumes much less memory than the System.Text.Json-based methods, with 5.14 MB allocated. While the UseUserDefinedObjectWithNewtonsoftJson() method consumes almost the same amount of memory as the System.Text.Json-based methods with 20.25 MB allocated.

The slowest method for this benchmark test is the UseJArrayParseInNewtonsoftJson() method, with an average time of 709.25 ms. This method also allocates the most memory among all the tested methods, with 77.72 MB allocated.

Overall, we can see that the UseFileOpenReadTextWithSystemTextJson() method is the best choice to read and parse a JSON file in C#.

Conclusion

In this article, we explored six different methods that we can use to read and parse a JSON file in C# with examples. Additionally, we utilized the BenchmarkDotNet library to compare the performance of these methods. This article provides a comprehensive guide for developers to understand how to read and parse JSON files in C# and choose the best approach for their use case.

To learn how to perform the reverse process, that is, writing a JSON string to a file, please visit How to Write JSON Into a File in C#.

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!