Read JSON data from URL and Populate DropDownList using C# and VB.Net in ASP.Net

Last Reply 5 months ago By dharmendr

Posted 5 months ago

i need to access APi Data and fetched need to show in dropdown.

This is my API URL

http://apistaging.ticketsimply.com/gds/api/cities.json?api_key=TSAPILAXMIHOLIDAYS321

It is returning like

{"result":[["id","name","origin_count","destination_count"],[1,"A S Peta",0,0],[2,"Aachara",0,0],[3,"Aanjangaon",0,0],[4,"Aanjar",0,0],[5,"Aathankarai",0,0],[6,"Abu",0,0],[7,"Abu Road",0,0]]}

 

Posted 5 months ago

Hi dilipsharm,

Check this example. Now please take its reference and correct your code.

I have refered the below article to read the data from url.

Read (Parse) JSON data from URL in ASP.Net using C# and VB.Net

HTML

<asp:DropDownList runat="server" ID="ddlItems">
</asp:DropDownList>

Namespaces

C#

using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

VB.Net

Imports System.Net
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        string json = (new WebClient()).DownloadString("http://apistaging.ticketsimply.com/gds/api/cities.json?api_key=TSAPILAXMIHOLIDAYS321");
        object result = JsonConvert.DeserializeObject<object>(json.Replace("{\"result\":", "").Replace("}", ""));
        JToken[] jArray = ((result as JArray) as JToken).ToArray();
        List<ListItem> items = new List<ListItem>();
        for (int i = 1; i < jArray.Length; i++)
        {
            items.Add(new ListItem { Text = jArray[i][1].ToString().Replace("\"", ""), Value = jArray[i][0].ToString().Replace("\"", "") });
        }
        ddlItems.DataSource = items;
        ddlItems.DataTextField = "Text";
        ddlItems.DataValueField = "Value";
        ddlItems.DataBind();
    }
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim json As String = (New WebClient()).DownloadString("http://apistaging.ticketsimply.com/gds/api/cities.json?api_key=TSAPILAXMIHOLIDAYS321")
        Dim result As Object = JsonConvert.DeserializeObject(Of Object)(json.Replace("{""result"":", "").Replace("}", ""))
        Dim jArray As JToken() = (TryCast((TryCast(result, JArray)), JToken)).ToArray()
        Dim items As List(Of ListItem) = New List(Of ListItem)()
        For i As Integer = 1 To jArray.Length - 1
            items.Add(New ListItem With {
                .Text = jArray(i)(1).ToString().Replace("""", ""),
                .Value = jArray(i)(0).ToString().Replace("""", "")
            })
        Next

        ddlItems.DataSource = items
        ddlItems.DataTextField = "Text"
        ddlItems.DataValueField = "Value"
        ddlItems.DataBind()
    End If
End Sub

Screenshot