Hi nauna,
Use WebClient to read the json from the api.
Then deserialize the string. If simple then deserialize to DataTable else to class object.
Then loop through the result and insert in database.
Check the example created using below article.
Namespaces
C#
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Net;
using Newtonsoft.Json;
VB.Net
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.Net
Imports Newtonsoft.Json
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
string json = (new WebClient()).DownloadString("https://raw.githubusercontent.com/aspsnippets/test/master/Customers.json");
DataTable dt = JsonConvert.DeserializeObject<DataTable>(json);
for (int i = 0; i < dt.Rows.Count; i++)
{
string constr = ConfigurationManager.ConnectionStrings["conster"].ConnectionString;
using (SqlConnection conn = new SqlConnection(constr))
{
string sql = "INSERT INTO tblCustomers VALUES(@Name, @Country)";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("@Name", dt.Rows[i]["Name"].ToString());
cmd.Parameters.AddWithValue("@Country", dt.Rows[i]["Country"].ToString());
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
ServicePointManager.Expect100Continue = True
ServicePointManager.SecurityProtocol = CType(3072, SecurityProtocolType)
Dim json As String = (New WebClient()).DownloadString("https://raw.githubusercontent.com/aspsnippets/test/master/Customers.json")
Dim dt As DataTable = JsonConvert.DeserializeObject(Of DataTable)(json)
For i As Integer = 0 To dt.Rows.Count - 1
Dim constr As String = ConfigurationManager.ConnectionStrings("conster").ConnectionString
Using conn As SqlConnection = New SqlConnection(constr)
Dim sql As String = "INSERT INTO tblCustomers VALUES(@Name, @Country)"
Using cmd As SqlCommand = New SqlCommand(sql, conn)
cmd.Parameters.AddWithValue("@Name", dt.Rows(i)("Name").ToString())
cmd.Parameters.AddWithValue("@Country", dt.Rows(i)("Country").ToString())
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
End Using
End Using
Next
End If
End Sub