Web api lec 18
Web api lec 18
2. JSON
JSON (JavaScript Object Notation) is a lightweight data format used for data interchange. It's easy to
read and write for humans and easy to parse and generate for machines.
3. LINQ
Language Integrated Query (LINQ) in C# allows querying objects, databases, XML, or JSON. It provides a
way to filter, select, and transform data in a readable and maintainable way.
4. Three-Step Approach
1. Open Visual Studio and select File > New > Project.
2. Choose the ASP.NET Core Web Application template.
3. Select Web Application (Model-View-Controller).
4. Name your project and click Create.
Code: ApiService.cs
This service will handle HTTP requests to the Web API.
using System.Net.Http;
using System.Threading.Tasks;
namespace YourProject.Services
{
public class ApiService
{
private readonly HttpClient _httpClient;
Code: JsonProcessor.cs
This class parses JSON and queries it using LINQ.
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
namespace YourProject.Utilities
{
public static class JsonProcessor
{
public static List<dynamic> ProcessJson(string jsonData)
{
var jsonDocument = JsonDocument.Parse(jsonData);
var jsonArray = jsonDocument.RootElement.EnumerateArray();
return jsonArray
.Select(item => new
{
Id = item.GetProperty("id").GetInt32(),
Title = item.GetProperty("title").GetString(),
Body = item.GetProperty("body").GetString()
})
.Cast<dynamic>()
.ToList();
}
}
}
using Microsoft.AspNetCore.Mvc;
using YourProject.Services;
using YourProject.Utilities;
namespace YourProject.Controllers
{
public class DataController : Controller
{
private readonly ApiService _apiService;
return View(processedData);
}
}
}
Razor View
Create a Razor View Index.cshtml to display the data in a table.
html
@model List<dynamic>
<table>
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Body</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>@item.Id</td>
<td>@item.Title</td>
<td>@item.Body</td>
</tr>
}
</tbody>
</table>
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace YourProject.Helpers
{
public static class ApiHelper
{
public static async Task<string> FetchJsonDataAsync(string apiUrl)
{
using (HttpClient client = new HttpClient())
{
var response = await client.GetAsync(apiUrl);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
throw new Exception("Error fetching JSON data.");
}
}
}
}
Step 2: Parse JSON Data Using LINQ
Code: JsonProcessor.cs
Process JSON using Newtonsoft.Json.
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
namespace YourProject.Helpers
{
public static class JsonProcessor
{
public static List<dynamic> ProcessJson(string jsonData)
{
var jsonArray = JArray.Parse(jsonData);
return jsonArray
.Select(item => new
{
Id = (int)item["id"],
Title = (string)item["title"],
Body = (string)item["body"]
})
.Cast<dynamic>()
.ToList();
}
}
}
using System;
using System.Threading.Tasks;
using YourProject.Helpers;
if (!IsPostBack)
{
GridView1.DataBind();
Code: ApiHelper.cs
Add a helper class to fetch JSON data.
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace YourProject.Helpers
{
public static class ApiHelper
{
public static async Task<string> FetchJsonDataAsync(string apiUrl)
{
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync(apiUrl);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
throw new Exception("Error fetching JSON data.");
}
}
}
}
3. Parse and Process JSON Using LINQ
Use Newtonsoft.Json or System.Text.Json for parsing JSON. For simplicity, we'll use
Newtonsoft.Json.
Code: JsonProcessor.cs
Add a helper class to parse JSON and process it using LINQ.
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
namespace YourProject.Helpers
{
public static class JsonProcessor
{
public static List<dynamic> ProcessJson(string jsonData)
{
var jsonArray = JArray.Parse(jsonData);
return jsonArray
.Select(item => new
{
Id = (int)item["id"],
Title = (string)item["title"],
Body = (string)item["body"]
})
.Cast<dynamic>()
.ToList();
}
}
}
4. Create the User Interface (GridView)
In the DisplayData.aspx file, add a GridView control.
Markup: DisplayData.aspx
html
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="DisplayData.aspx.cs" Inherits="YourProject.DisplayData" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title>Display Data</title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="True" />
</form>
</body>
</html>
Code-Behind: DisplayData.aspx.cs
csharp
using System;
using System.Threading.Tasks;
using YourProject.Helpers;
json
[
{ "id": 1, "title": "Title 1", "body": "Body 1" },
{ "id": 2, "title": "Title 2", "body": "Body 2" },
{ "id": 3, "title": "Title 3", "body": "Body 3" }
]