Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Products
  • Resources
    • Cheatsheets
    • Tech Comparisons
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# ASP.NET MVC ASP.NET Web Forms C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet General Web Development HTML, CSS HTML/CSS Java JavaScript JavaScript, HTML, CSS JavaScript, Node.js Node.js
      Python Python 3.11, Pandas, SQL Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. ASP.NET Core
  4. Reading json data from file using Asp.Net

Reading json data from file using Asp.Net

Date- Dec 22,2022 Updated Feb 2026 5673 Free Download Pay & Download
AspNet StreamReader

Understanding JSON and Its Importance

JSON is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. It is commonly used in web applications for transmitting data between the client and server. JSON files can be utilized for various purposes, such as configuration files, storing application settings, or even as a simple database for small applications.

In an ASP.NET Core application, reading JSON data from files can simplify data management and enhance flexibility. For example, you might have a configuration file that stores various settings for your application, or a data file that contains information about countries, products, or users.

Prerequisites

Before diving into the code, ensure you have the following prerequisites:

  • Visual Studio or any other IDE that supports ASP.NET Core.
  • Basic knowledge of C# and ASP.NET Core.
  • Newtonsoft.Json library installed in your project, which can be added via NuGet Package Manager.

Reading JSON Data from a File

To read JSON data from a file in an ASP.NET Core application, we will use the StreamReader class along with the Newtonsoft.Json library to deserialize the JSON content into C# objects. For this tutorial, we will create a JSON file named countrycodes.json and place it in the Content folder of the project.

Reading json data from file using AspNet

The structure of our JSON file might look something like this:

[
  {
    "countryname": "United States",
    "continent": "North America",
    "currency": "USD",
    "capital": "Washington, D.C.",
    "timezoneincapital": "UTC-5"
  },
  {
    "countryname": "Germany",
    "continent": "Europe",
    "currency": "EUR",
    "capital": "Berlin",
    "timezoneincapital": "UTC+1"
  }
]

Next, we will implement the code in our controller to read this JSON file. Below is an example of how to do this:

using JsonReader.Models;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using Microsoft.AspNetCore.Mvc;

namespace JsonReader.Controllers {
    public class HomeController : Controller {
        public IActionResult Index() {
            // Reading file from server
            List items = new List();
            using (StreamReader r = new StreamReader(Path.Combine(Directory.GetCurrentDirectory(), "Content/countrycodes.json"))) {
                string json = r.ReadToEnd();
                items = JsonConvert.DeserializeObject>(json);
            }
            return View(items);
        }
    }
}

In this code, we use StreamReader to read the contents of the JSON file and then deserialize it into a list of CountryCode objects.

Creating the CountryCode Model

To deserialize the JSON data correctly, we need to create a model that matches the structure of our JSON. Here is how you can define the CountryCode model:

namespace JsonReader.Models {
    public class CountryCode {
        public string CountryName { get; set; }
        public string Continent { get; set; }
        public string Currency { get; set; }
        public string Capital { get; set; }
        public string TimezoneInCapital { get; set; }
    }
}

Note that property names in the model should match the JSON keys. C# naming conventions typically use PascalCase, but JSON keys are often in camelCase. You can use attributes from the Newtonsoft.Json library to handle these discrepancies if needed.

Displaying the Data in the View

After reading and parsing the JSON data, the next step is to display it in a view. We can create a simple Razor view to show the country codes. Below is an example of what the view might look like:

@model List

Country Codes

@foreach (var item in Model) { }
Country Name Continent Currency Capital Timezone in Capital
@item.CountryName @item.Continent @item.Currency @item.Capital @item.TimezoneInCapital
Reading json data from file using AspNet 2

This will render a table displaying the country codes that were read from the JSON file. Make sure to run your application to see the output on the browser.

Edge Cases & Gotchas

While working with JSON files, there are several edge cases and potential issues to consider:

  • File Not Found: Ensure that the JSON file path is correct. If the file cannot be found, it will throw an exception. You can implement error handling to manage this gracefully.
  • Malformed JSON: If the JSON data is not well-formed, deserialization will fail. Always validate the JSON structure before reading it.
  • Data Type Mismatches: Ensure that the data types in your model match those in the JSON. For example, if a field is expected to be an integer but is provided as a string, it may cause runtime errors.

Performance & Best Practices

When working with JSON in ASP.NET Core applications, it's essential to follow best practices to ensure optimal performance:

  • Use Asynchronous I/O: Consider using asynchronous file reading methods to avoid blocking the main thread, especially when dealing with large files.
  • Cache JSON Data: If the JSON data does not change frequently, consider caching the deserialized objects to reduce file I/O overhead.
  • Validate JSON Structure: Before deserializing, validate the JSON structure to catch issues early and avoid exceptions during runtime.
  • Use Strongly Typed Models: Always create models that represent the structure of your JSON data to ensure type safety and reduce errors.

Conclusion

In this tutorial, we explored how to read JSON data from a file in an ASP.NET Core application. We covered the following key points:

  • JSON is a widely used format for data interchange in web applications.
  • Using StreamReader and Newtonsoft.Json, we can easily read and deserialize JSON data.
  • Properly structuring your models and handling edge cases can prevent runtime errors.
  • Best practices, such as caching and using asynchronous methods, can enhance performance.

S
Shubham Batra
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

What is asp.net in web development
Apr 25, 2022
Sending FCM Mobile Notification in Asp.net for Android
Dec 18, 2021
Performing CRUD Operations with DB2 in ASP.NET Core: A Comprehensive Guide
Apr 07, 2026
Connecting ASP.NET Core to DB2: A Step-by-Step Guide
Apr 07, 2026
Previous in ASP.NET Core
Web Api in Asp.net core
Next in ASP.NET Core
JWT Token Authentication And Authorizations In Web API
Buy me a pizza

Comments

🔥 Trending This Month

  • 1
    CWE-269: Improper Privilege Management - Implementing the … 310 views
  • 2
    Elasticsearch Integration in ASP.NET Core - Full-Text Sear… 238 views
  • 3
    Building Custom Bedrock Add-Ons with JavaScript: A Complet… 1,913 views
  • 4
    Error-An error occurred while processing your request in .… 11,945 views
  • 5
    Fix Gemini API Error 429: Quota Exceeded on Free Tier (Sys… 808 views
  • 6
    Integrating Google reCAPTCHA Validation in ASP.NET MVC 6,451 views
  • 7
    Integrating Google reCAPTCHA v3 in ASP.NET Core for Seamle… 596 views

On this page

🎯

Interview Prep

Ace your ASP.NET Core interview with curated Q&As for all levels.

View ASP.NET Core Interview Q&As

More in ASP.NET Core

  • How to Encrypt and Decrypt Password in Asp.Net 26674 views
  • Exception Handling Asp.Net Core 21706 views
  • HTTP Error 500.31 Failed to load ASP NET Core runtime 21158 views
  • How to implement Paypal in Asp.Net Core 20122 views
  • Task Scheduler in Asp.Net core 18192 views
View all ASP.NET Core posts →

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1780
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Products
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • ASP.NET MVC
  • ASP.NET Web Forms
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • General Web Development
  • HTML, CSS
  • HTML/CSS
  • Java
  • JavaScript
  • JavaScript, HTML, CSS
  • JavaScript, Node.js
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor