22
Dec
2022
2022
Reading json data from file using Asp.Net
by Shubham Batra
981
JSON File-
So for this tutorial we will use a file which will have json data in it and we will place that in the Content folder of the project. As you can see in the image below
Now for reading this json file in C# we have to use StreamReader class. You have to go to controller and copy this code
using JsonReader.Models; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.IO; using System.Linq; using System.Web; using System.Web.Mvc; namespace JsonReader.Controllers { public class HomeController : Controller { public ActionResult Index() { //Reading file from server List<CountryCode> items = new List<CountryCode>(); using (StreamReader r = new StreamReader(Server.MapPath("/Content/countrycodes.json"))) { string json = r.ReadToEnd(); items = JsonConvert.DeserializeObject<List<CountryCode>>(json); } return View(items); } } }
For parse the json here we are using NewtonSoft.Json Library which you can get from nuget packages. You have to also create following class to parse json data to list object
using System.Collections.Generic; using System.Linq; using System.Web; 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;} } }
Now run the application and you will be able to see the data being read from json file to list object which we can show on screen like the screenshot below
So this is how we can read json data from json file and parse in list object in asp.net.