code-maze.com Open in urlscan Pro
2606:4700:3108::ac42:28d8  Public Scan

URL: https://code-maze.com/csharp-read-and-process-json-file/
Submission: On October 27 via manual from MX — Scanned from DE

Form analysis 3 forms found in the DOM

GET https://code-maze.com/

<form role="search" class="et-search-form" method="get" action="https://code-maze.com/">
  <input type="search" class="et-search-field" placeholder="Search" value="" name="s" title="Search for:">
  <button class="et-search-submit"></button>
</form>

GET https://code-maze.com/

<form role="search" class="et-search-form" method="get" action="https://code-maze.com/">
  <input type="search" class="et-search-field" placeholder="Search" value="" name="s" title="Search for:">
  <button class="et-search-submit"></button>
</form>

POST

<form id="mc4wp-form-1" class="mc4wp-form mc4wp-form-1018 mc4wp-form-theme mc4wp-form-theme-dark" method="post" data-id="1018" data-name="Sign Up Widget Right">
  <div class="mc4wp-form-fields">
    <div style="background:white; padding:20px;    border-top-width: 6px;
    border-top-style: solid;    border-color: #3e5062;border-radius: 3px;">
      <div style="width:198px; margin: 0 auto;">
        <div>
          <img src="https://code-maze.com/wp-content/uploads/2021/03/booklet-200px-width-min.png">
        </div>
        <div hidden="">
          <label>Freebies</label>
          <label>
            <input name="INTERESTS[bfa5d3e4fb][]" type="checkbox" value="4bb19d9837"> <span>HttpBook</span>
          </label>
          <label>
            <input name="INTERESTS[bfa5d3e4fb][]" type="checkbox" value="bb955660c3" checked="true"> <span>NetCoreCheatSheet</span>
          </label>
          <label>
            <input name="INTERESTS[bfa5d3e4fb][]" type="checkbox" value="29c29385a0"> <span>AngularCheatCheet</span>
          </label>
          <label>
            <input name="INTERESTS[bfa5d3e4fb][]" type="checkbox" value="69ac66c187"> <span>TroyHuntInfographic</span>
          </label>
          <label>
            <input name="INTERESTS[bfa5d3e4fb][]" type="checkbox" value="939b3d82a7"> <span>TheDefinitiveGuideToCI</span>
          </label>
          <label>
            <input name="INTERESTS[bfa5d3e4fb][]" type="checkbox" value="af4dfb68dc"> <span>AngularMaterial</span>
          </label>
          <label>
            <input name="INTERESTS[bfa5d3e4fb][]" type="checkbox" value="c8a8234491"> <span>HomePageSub</span>
          </label>
        </div>
        <p style="text-align:center;"> Join our 20k+ community of experts and learn about our <strong>Top 16 Web API Best Practices</strong>. </p>
        <div style="display: inline-block; margin-top:-20px;">
          <input type="email" id="email" name="EMAIL" required="" placeholder="Email Address" style="padding-top:9px;padding-bottom:10px; float:left; width:198px; margin-top:10px; font-size:13px; align:center;">
          <input type="submit" class="learn-more" value="Subscribe" style="width:198px; margin-top:10px; padding:6px;font-size:20px;">
        </div>
      </div>
    </div>
  </div><label style="display: none !important;">Leave this field empty if you're human: <input type="text" name="_mc4wp_honeypot" value="" tabindex="-1" autocomplete="off"></label><input type="hidden" name="_mc4wp_timestamp"
    value="1698435729"><input type="hidden" name="_mc4wp_form_id" value="1018"><input type="hidden" name="_mc4wp_form_element_id" value="mc4wp-form-1">
  <div class="mc4wp-response"></div>
</form>

Text Content

WE VALUE YOUR PRIVACY

We and our partners store and/or access information on a device, such as cookies
and process personal data, such as unique identifiers and standard information
sent by a device for personalised ads and content, ad and content measurement,
and audience insights, as well as to develop and improve products. With your
permission we and our partners may use precise geolocation data and
identification through device scanning. You may click to consent to our and our
partners’ processing as described above. Alternatively you may click to refuse
to consent or access more detailed information and change your preferences
before consenting. Please note that some processing of your personal data may
not require your consent, but you have a right to object to such processing.
Your preferences will apply to this website only. You can change your
preferences at any time by returning to this site or visit our privacy policy.
MORE OPTIONSDISAGREEAGREE
The one and only resource you'll ever need to learn APIs: Ultimate ASP.NET Core
Web API - SECOND EDITION! 🔥 Want to kick start your web development in C#?
Check out BLAZOR WEBASSEMBLY COURSE! 🔥
 * 
 * 
 * 
 * 


 * Home
 * Book V2 📙
 * Blazor WASM 🔥
 * Guides
   * ASP.NET Core
     * ASP.NET Core Series
     * GraphQL ASP.NET Core
     * ASP.NET Core MVC Series
     * Testing ASP.NET Core Applications
     * EF Core Series
     * HttpClient with ASP.NET Core
     * Azure with ASP.NET Core
   * Security
     * ASP.NET Core Identity Series
     * IdentityServer4, OAuth, OIDC Series
     * Angular with ASP.NET Core Identity
   * Blazor WebAssembly
   * .NET
     * .NET Collections
   * Best Practices
     * SOLID Principles in C#
     * ASP.NET Core Web API Best Practices
     * Top REST API Best Practices
     * Angular Development Best Practices
     * 10 Things You Should Avoid in Your ASP.NET Core Controllers
   * C# Series
     * C# Back to Basics
     * C# Intermediate
     * Design Patterns in C#
     * Sorting Algorithms in C#
   * Docker Series
   * Angular
     * Angular Series
     * Angular Material Series
   * HTTP Series
 * We Are Hiring!
   * .NET/C# Author
   * .NET/C# Editor
 * About
   * About Us
   * Archives
   * Our Editors
   * Leave Us a Review
   * Code Maze Reviews
   * Contact Us

Select Page

 * 
 * 
 * 
 * 


 * Home
 * Book V2 📙
 * Blazor WASM 🔥
 * Guides
   * ASP.NET Core
     * ASP.NET Core Series
     * GraphQL ASP.NET Core
     * ASP.NET Core MVC Series
     * Testing ASP.NET Core Applications
     * EF Core Series
     * HttpClient with ASP.NET Core
     * Azure with ASP.NET Core
   * Security
     * ASP.NET Core Identity Series
     * IdentityServer4, OAuth, OIDC Series
     * Angular with ASP.NET Core Identity
   * Blazor WebAssembly
   * .NET
     * .NET Collections
   * Best Practices
     * SOLID Principles in C#
     * ASP.NET Core Web API Best Practices
     * Top REST API Best Practices
     * Angular Development Best Practices
     * 10 Things You Should Avoid in Your ASP.NET Core Controllers
   * C# Series
     * C# Back to Basics
     * C# Intermediate
     * Design Patterns in C#
     * Sorting Algorithms in C#
   * Docker Series
   * Angular
     * Angular Series
     * Angular Material Series
   * HTTP Series
 * We Are Hiring!
   * .NET/C# Author
   * .NET/C# Editor
 * About
   * About Us
   * Archives
   * Our Editors
   * Leave Us a Review
   * Code Maze Reviews
   * Contact Us


HOW TO READ AND PARSE A JSON FILE IN C#

Posted by Januarius Njoku | Updated Date Mar 8, 2023 | 2

Want to build great APIs? Or become even better at it? Check our Ultimate
ASP.NET Core Web API program and learn how to create a full production-ready
ASP.NET Core API using only the latest .NET technologies. Bonus materials
(Security book, Docker book, and other bonus files) are included in the Premium
package!

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.

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

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:

Support Code Maze on Patreon to get rid of ads and get the best discounts on our
products!




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


[
    {
        "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; }
}
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; } }


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; }
}
public class Course { public string Name { get; set; } = string.Empty; public
int CreditUnits { get; set; } public int NumberOfStudents { get; set; } }


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;
}
}
public class ReadAndParseJsonFileWithNewtonsoftJson { private readonly string
_sampleJsonFilePath; public ReadAndParseJsonFileWithNewtonsoftJson(string
sampleJsonFilePath) { _sampleJsonFilePath = sampleJsonFilePath; } }


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;
}
public List<Teacher> UseUserDefinedObjectWithNewtonsoftJson() { using
StreamReader reader = new(_sampleJsonFilePath); var json = reader.ReadToEnd();
List<Teacher> teachers = JsonConvert.DeserializeObject<List<Teacher>>(json);
return teachers; }


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.

Wanna join Code Maze Team, help us produce more awesome .NET/C# content and get
paid? >> JOIN US! <<

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;
}
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; }


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.

Wanna join Code Maze Team, help us produce more awesome .NET/C# content and get
paid? >> JOIN US! <<


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;
}
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; }


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.

Wanna join Code Maze Team, help us produce more awesome .NET/C# content and get
paid? >> JOIN US! <<

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



public class ReadAndParseJsonFileWithSystemTextJson
{
private readonly string _sampleJsonFilePath;

public ReadAndParseJsonFileWithSystemTextJson(string sampleJsonFilePath)
{
_sampleJsonFilePath = sampleJsonFilePath;
}
}
public class ReadAndParseJsonFileWithSystemTextJson { private readonly string
_sampleJsonFilePath; public ReadAndParseJsonFileWithSystemTextJson(string
sampleJsonFilePath) { _sampleJsonFilePath = sampleJsonFilePath; } }


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
};
private readonly JsonSerializerOptions _options = new() {
PropertyNameCaseInsensitive = true };


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;
}
public List<Teacher> UseFileReadAllTextWithSystemTextJson() { var json =
File.ReadAllText(_sampleJsonFilePath); List<Teacher> teachers =
JsonSerializer.Deserialize<List<Teacher>>(json, _options); return teachers; }


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;
}
public List<Teacher> UseFileOpenReadTextWithSystemTextJson() { using FileStream
json = File.OpenRead(_sampleJsonFilePath); List<Teacher> teachers =
JsonSerializer.Deserialize<List<Teacher>>(json, _options); return teachers; }


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.

Wanna join Code Maze Team, help us produce more awesome .NET/C# content and get
paid? >> JOIN US! <<

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;
}
public List<Teacher> UseStreamReaderWithSystemTextJson() { using StreamReader
streamReader = new(_sampleJsonFilePath); var json = streamReader.ReadToEnd();
List<Teacher> teachers = JsonSerializer.Deserialize<List<Teacher>>(json,
_options); return teachers; }


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.

Wanna join Code Maze Team, help us produce more awesome .NET/C# content and get
paid? >> JOIN US! <<

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 |
| 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 |


|                                 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.

Wanna join Code Maze Team, help us produce more awesome .NET/C# content and get
paid? >> JOIN US! <<

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!


Want to build great APIs? Or become even better at it? Check our Ultimate
ASP.NET Core Web API program and learn how to create a full production-ready
ASP.NET Core API using only the latest .NET technologies. Bonus materials
(Security book, Docker book, and other bonus files) are included in the Premium
package!

Share:



2 Comments

Oldest
Newest Most Voted
Inline Feedbacks
View all comments
View Comments
Load More Comments



Freebies HttpBook NetCoreCheatSheet AngularCheatCheet TroyHuntInfographic
TheDefinitiveGuideToCI AngularMaterial HomePageSub

Join our 20k+ community of experts and learn about our Top 16 Web API Best
Practices.


Leave this field empty if you're human:










© Copyright code-maze.com 2016 - 2023

 
wpDiscuz


Insert
Â