How to Read (Parse) JSON data from URL in MVC C#

In this tutorial, we will learn how to read (parse) json data in to C# MVC.

Steps involved in this tutorial:
1) Get Json URL which will provide data
2) Generate the C# Mapper class for the Json result data or Json response.
3) Deserialize Json result to C# mapper class.
4) Pass this mapped data to view
5) Display this Json result data to user in a view page


We are going to use this demo URL:



Below is the json response in browser:




Now in order to access the data from JSON, first we need perform below operations:
1) Hit the JSON URL
2) Get the response
3) Parse this response to a C# class
4) Pass this result to view and read this C# object data in view
5) Display the data to user


Now we have URL, we will create the C# class based on its structure. We can generate the C# class online by just pasting this URL into: http://json2csharp.com/ Then click on generate. C# class will be generated based on the Json's response structure.



Below class we will add in our Model->JsonModel folder

public class RootObject
{
    public int userId { get; set; }
    public int id { get; set; }
    public string title { get; set; }
    public bool completed { get; set; }
}


Now we will go ahead and write below method in our controller class.
This will invoke the URL, will get the data, parse it into rootObject class and will return the parsed data. In order to get the webClient and parse the json result data we need to include below namespace in our controller class.
using Newtonsoft.Json;
using System.Net;


using Newtonsoft.Json; 
using System.Net;

 
public ActionResult GetJsonDataModel()
        {
            var webClient = new WebClient();
            webClient.Headers.Add(HttpRequestHeader.Cookie, "cookievalue");
            var json = webClient.DownloadString(@"https://jsonplaceholder.typicode.com/todos/1");
            Models.JsonModel.RootObject objJson = JsonConvert.DeserializeObject<Models.JsonModel.RootObject>(json);

            return View(objJson);
        }


Now we need to add view to show the json output in view.
Right click on method GetJsonDataModel() and click on Add view, and click add view.


@model ProjectDemoJsonURL.Models.JsonModel.RootObject
@{
    ViewBag.Title = "GetJsonDataModel";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>GetJsonDataModel</h2>
@{ 
<table>
    <tr>
        <th>userId</th>
        <th>id</th>
        <th>title</th>
        <th>completed</th>
    </tr>
    <tr>
        <th>@Model.userId</th>
        <th>@Model.id</th>
        <th>@Model.title</th>
        <th>@Model.completed</th>
    </tr>
</table>
}




Thanks for reading the blog. Now we are able to parse the json data from URL into MVC C# successfully. I hope this helps.

Comments