In this article I will explain with an example, how to read
JSON file using C# in ASP.Net MVC.
The JSON File
Following is the
JSON saved inside a
JSON file inside Project folder.
[
{
"CustomerId": 1,
"Name": "John Hammond",
"Country": "United States"
},
{
"CustomerId": 2,
"Name": "Mudassar Khan",
"Country": "India"
},
{
"CustomerId": 3,
"Name": "Suzanne Mathews",
"Country": "France"
},
{
"CustomerId": 4,
"Name": "Robert Schidner",
"Country": "Russia"
}
]
Model
The Model class consists of the following properties.
public class CustomerModel
{
public int CustomerId { get; set; }
public string Name { get; set; }
public string Country { get; set; }
}
Namespaces
You will need to import the following namespaces.
using System.IO;
using System.Web.Script.Serialization;
Controller
The Controller consists of following Action method.
Action method for handling GET operation
Inside this Action method, the contents of the
JSON file are read using
StreamReader class object from the
Files Folder (Directory).
Then, an object of
JavaScriptSerializer class is created and the
JSON string is read from
StreamReader using the
ReadToEnd method and is converted to Generic List of
CustomerModel class object using
Deserialize method of
JavaScriptSerializer class.
Finally, the Generic List of CustomerModel class object is returned to the View.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
using (StreamReader reader = new StreamReader(Server.MapPath("~/Files/Customers.json")))
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<CustomerModel> customers = serializer.Deserialize<List<CustomerModel>>(reader.ReadToEnd());
return View(customers);
}
}
}
View
HTML Markup
Inside the View, in the very first line the CustomerModel class is declared as IEnumerable which specifies that it will be available as a Collection.
For displaying the records, an HTML Table is used. A loop will be executed over the Model which will generate the HTML Table rows with the Customer records.
@using Read_Json_File_MVC.Models;
@model IEnumerable<CustomerModel>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<table cellpadding="0" cellspacing="0">
<tr>
<th>CustomerId</th>
<th>Name</th>
<th>Country</th>
</tr>
@foreach (CustomerModel customer in Model)
{
<tr>
<td>@customer.CustomerId</td>
<td>@customer.Name</td>
<td>@customer.Country</td>
</tr>
}
</table>
</body>
</html>
Screenshot
Downloads