Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • 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. How to read json file in asp.net Core

How to read json file in asp.net Core

Date- Mar 07,2024 Updated Mar 2026 7184 Free Download Pay & Download
Reading json file

Reading JSON File in ASP.NET Core

In this article we will see how we can read json file and convert that into c# object in asp.net core.

In this article, we'll explore a simple HomeController class in an ASP.NET Core application that reads data from a JSON file.

The Code

Let's take a closer look at the Product class    which we will use to deserialize the json data.

        
      namespace JsonReaderCore.Models
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public string Description { get; set; }
    }
}

        
    

This is the controller code where we will read the sample json file and try to convert that to c# list object

        
           using JsonReaderCore.Models;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Diagnostics;

namespace JsonReaderCore.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly IWebHostEnvironment _webHostEnvironment;

     
        public HomeController(ILogger<HomeController> logger, IWebHostEnvironment webHostEnvironment)
        {
            _logger = logger;
            _webHostEnvironment = webHostEnvironment;
        }

        public IActionResult Index()
        {
            var filePath = Path.Combine(_webHostEnvironment.WebRootPath, "Dummy.json");
            var result= JsonFileReader.ReadJsonFile<List<Product>>(filePath);
            return View(result);
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

        
    

Add JsonFileReader class in your project and copy following code

using System.IO;

using Newtonsoft.Json;

namespace JsonReaderCore.Models
{

    public class JsonFileReader
    {
        public static T ReadJsonFile<T>(string fileName)
        {
            var filePath = Path.Combine(Directory.GetCurrentDirectory(), fileName);

            using (var streamReader = new StreamReader(filePath))
            using (var jsonReader = new JsonTextReader(streamReader))
            {
                var serializer = new JsonSerializer();
                return serializer.Deserialize<T>(jsonReader);
            }
        }
    }
}

How to read json file in aspnet Core

Add dummy.json file in the wwwroot folder in your project and add some dummy json in that

Explanation

This code resides in a controller class, HomeController. It defines an Index action that reads JSON data from a file named dummy.json.

Let's break down the key components of the code:

  • StreamReader: Initializes a new instance of the StreamReader class to read from the specified file path.
  • Server.MapPath: Maps the virtual path to a physical path on the server. In this case, it resolves the path to the countrycodes.json file.
  • JsonConvert.DeserializeObject: Deserializes the JSON data read from the file into a List<CountryCode> object.
  • return View(items): Passes the deserialized data to the corresponding view for further processing or rendering.

This code assumes the existence of a class named CountryCode representing the structure of the JSON data. Make sure to replace it with your actual class definition.

  1. using System.IO;: This line imports the System.IO namespace, which provides classes for working with files and directories.

  2. using Newtonsoft.Json;: This line imports the Newtonsoft.Json namespace, which contains classes for JSON serialization and deserialization.

  3. namespace JsonReaderCore.Models: This code resides within the JsonReaderCore.Models namespace.

  4. public class JsonFileReader: This is a public class named JsonFileReader, which contains a static method ReadJsonFile.

  5. public static T ReadJsonFile<T>(string fileName): This method takes a generic type T and a string parameter fileName, representing the name of the JSON file to be read. It returns an object of type T, which is deserialized from the JSON file.

  6. var filePath = Path.Combine(Directory.GetCurrentDirectory(), fileName);: This line constructs the full file path by combining the current directory path with the provided fileName.

  7. using (var streamReader = new StreamReader(filePath)): This line creates a StreamReader to read from the file specified by filePath. The using statement ensures that the StreamReader is disposed of properly after use.

  8. using (var jsonReader = new JsonTextReader(streamReader)): This line creates a JsonTextReader to read JSON data from the StreamReader. Again, the using statement ensures proper disposal after use.

  9. var serializer = new JsonSerializer();: This line creates a new instance of JsonSerializer, which is responsible for deserializing JSON data.

Conclusion

Reading JSON files in ASP.NET Core is a common task, and the provided code demonstrates a straightforward approach to achieve this. Feel free to adapt and customize it based on your specific requirements.

So this is how to read json file in asp.net core using a custom JsonFileReader class

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

Related Articles

How to read json file in asp.net mvc
Feb 05, 2024
Previous in ASP.NET Core
Authentication for swagger UI in production in ASP.Net Core 6.0
Next in ASP.NET Core
Sending Calendar Events Using .ICS File in ASP.NET
Buy me a pizza

Comments

🔥 Trending This Month

  • 1
    HTTP Error 500.32 Failed to load ASP NET Core runtime 6,939 views
  • 2
    Error-An error occurred while processing your request in .… 11,281 views
  • 3
    Comprehensive Guide to Error Handling in Express.js 236 views
  • 4
    ConfigurationBuilder does not contain a definition for Set… 19,464 views
  • 5
    Complete Guide to Creating a Registration Form in HTML/CSS 4,218 views
  • 6
    Mastering Unconditional Statements in C: A Complete Guide … 21,507 views
  • 7
    Mastering JavaScript Error Handling with Try, Catch, and F… 162 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 26077 views
  • Exception Handling Asp.Net Core 20798 views
  • HTTP Error 500.31 Failed to load ASP NET Core runtime 20303 views
  • How to implement Paypal in Asp.Net Core 19681 views
  • Task Scheduler in Asp.Net core 17582 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 | 1770
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
  • 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