Read and parse a Json File in C#

Matheus Mello
Matheus Mello
September 2, 2023
Cover Image for Read and parse a Json File in C#

How to Read and Parse a JSON File in C# 📝

Are you struggling to read and parse a large JSON file in C#? Don't worry, you're not alone! Many developers face this challenge when working with JSON data. In this blog post, we'll explore a common issue, provide easy solutions, and help you overcome this obstacle.

The Problem 🤔

One of our readers asked, "How does one read a very large JSON file into an array in C# to be split up for later processing?"

Our reader had already tried some code, but it crashed the program after a few lines. They suspected that the file size might be the culprit.

The Solution 💡

To address this problem, we need to improve the code and ensure it can handle the large JSON file. Here's an updated version of the code:

// If the file extension is a json file, it will execute the following code
if (fileExtension == ".json") 
{
    List<string> rawData = new List<string>(); // Use a List instead of a fixed-size array
    bool isInsideObject = false; // Track whether we're inside an object
    string currentValue = null; // Track the current value

    using (JsonTextReader reader = new JsonTextReader(new StreamReader(txtLocation.Text)))
    {
        while (reader.Read())
        {
            switch (reader.TokenType)
            {
                case JsonToken.StartObject:
                    isInsideObject = true;
                    break;
                case JsonToken.PropertyName:
                    if ((string)reader.Value == "vcc") // Only store the value if it's the desired property
                    {
                        reader.Read(); // Move to the property's value
                        currentValue = (string)reader.Value;
                    }
                    else
                    {
                        currentValue = null; // Reset the value if it's not the desired property
                    }
                    break;
                case JsonToken.EndObject:
                    isInsideObject = false;
                    if (currentValue != null)
                    {
                        rawData.Add(currentValue); // Add the value to the list
                        currentValue = null; // Reset the value for the next object
                    }
                    break;
            }
        }
    }
}

Let's break down the changes we made:

  1. Instead of using a fixed-size array (string[] rawData = new string[5]), we're now using a List<string> to store the values. This allows us to handle any number of values without worrying about array size limitations.

  2. We introduced a bool variable called isInsideObject to keep track of whether we're inside an object or not. This helps us ensure that we're only storing values from the desired property.

  3. We added a string variable called currentValue to store the value of the desired property temporarily. We only add this value to the list when we encounter the corresponding closing brace (JsonToken.EndObject).

  4. We used a switch statement to handle different tokens and take appropriate actions based on the token type. When we encounter a property name (JsonToken.PropertyName), we check if it matches the desired property ("vcc"). If it does, we store its associated value in currentValue. Otherwise, we reset currentValue to null.

By making these changes, we can read the JSON file and extract only the desired data into a list.

Summary 📚

To summarize, reading and parsing a JSON file in C# can be challenging, especially when dealing with large files. However, by using a JsonTextReader and making modifications to the code, we can overcome these challenges and extract only the necessary data.

Now it's your turn! Give the updated code a try and let us know if it helps you solve your problem. If you have any further questions or suggestions, feel free to leave a comment below. Happy coding! 💻✨

Take Your Tech Career to the Next Level

Our application tracking tool helps you manage your job search effectively. Stay organized, track your progress, and land your dream tech job faster.

Your Product
Product promotion

Share this article

More Articles You Might Like

Latest Articles

Cover Image for How can I echo a newline in a batch file?
batch-filenewlinewindows

How can I echo a newline in a batch file?

Published on March 20, 2060

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Cover Image for How do I run Redis on Windows?
rediswindows

How do I run Redis on Windows?

Published on March 19, 2060

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Cover Image for Best way to strip punctuation from a string
punctuationpythonstring

Best way to strip punctuation from a string

Published on November 1, 2057

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Cover Image for Purge or recreate a Ruby on Rails database
rakeruby-on-railsruby-on-rails-3

Purge or recreate a Ruby on Rails database

Published on November 27, 2032

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my