In this article we will explain how to read and write a json file in C# using Newtonsoft.Json.
This is very simple article having simple steps to read and write a json file in C#. To continue with this, first of all please install Newtonsoft.Json package. For demo purpose I have created a simple MVC application having a model, partial view, controller and a json file. We will list few youtube urls in json file, convert it into model using Newtonsoft.Json package and render it to partial view.
Add a class and name it VideoFeederModel. Copy below code.
public class VideoFeederModel
{
public string URL { get; set; }
public string Title { get; set; }
}
Add a json file and add below data.
[
{
"URL": "https://www.youtube.com/embed/NuWuNAb_4AM",
"Title": "E-Bill validitiy extension"
},
{
"URL": "https://www.youtube.com/embed/h8x0p0_aeiE",
"Title": "FAQ ON EMI RELIEF FAQ ON EMI MORATORIUM FAQ RBI MORATORIUM"
},
{
"URL": "https://www.youtube.com/embed/Ad8rUXaPmIc",
"Title": "RBI Moratorium Notification EMI Moratorium EMI Relief during lock down"
},
{
"URL": "https://www.youtube.com/embed/DuMxQUPTHvI",
"Title": "Corporate Affairs Relief due to COVID 19 Corona Analysis by CA Sri Niwash Jha"
},
{
"URL": "https://www.youtube.com/embed/wS27m-em_wQ",
"Title": "Relief to financial services, custom, and department of fisheries due to COVID19"
}
]
Add HomeController and add below method
public ActionResult VideoFeeder()
{
string filePath = Server.MapPath("~/JSON/VideoFeeder.json");
List<VideoFeederModel> model = JsonConvert.DeserializeObject<List<VideoFeederModel>>(System.IO.File.ReadAllText(filePath));
return PartialView("_VideoFeederPartial", model);
}
Now add a partial view and name it as "_VideoFeederPartial" and add below code.
@model List<VideoFeederModel>
<div class="row">
<div class="container content">
<h2>VIDEOS</h2>
@{ foreach (var item in Model)
{
<div class="video-container">
<p class="video-thumb">
<iframe class="video"
src="@item.URL" frameborder="1"
allow="accelerometer; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="">
</iframe>
</p>
<h4>@item.Title</h4>
</div>
}}
</div>
</div>
Now call the action ViewFeeder() in index.cshtml file and run the application. You will see video link added to your page. Hope this helps you.