In this article I will explain with an example, how to convert
JSON string to
DataSet using C# and VB.Net.
The
JSON string will be first downloaded from an API using
WebClient class and then will be converted to
DataSet using
Newtonsoft library.
Installing Newtonsoft package using Nuget
ASPSnippets Test API
The following API will be used in this article.
The API returns the following JSON.
[
{
"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"
}
]
Namespaces
You will need to import the following namespaces.
C#
using System.Net;
using System.Data;
using Newtonsoft.Json;
VB.Net
Imports System.Net
Imports System.Data
Imports Newtonsoft.Json
Converting JSON string to DataSet
Inside the Page_Load event handler, first the Security Protocol is set.
Then, the
JSON string is downloaded from an API using
DownloadString method of the
WebClient class.
DownloadString
It accepts the following parameter:
URL – The URL of the file to be downloaded.
The downloaded JSON string is then converted to
DataTable using
DeserializeObject method of
JsonConvert class.
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);
DataSet ds = new DataSet();
ds.Tables.Add(dt);
}
}
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)
Dim ds As DataSet = New DataSet()
ds.Tables.Add(dt)
End If
End Sub
Screenshot
Downloads