Get JSON return from URL in VB.NET

Asked

Viewed 199 times

1

I want to access the URL ("https://economia.awesomeapi.com.br/usd-brl") to fetch the json Ask field.

How do I request the URL and get the desired value in a variable?

I tried something like:

Dim json As String = GetWebPageText("https://economia.awesomeapi.com.br/usd-brl")



Private Function GetWebPageText(ByVal url As String) As String

    Try
        Dim Request As WebRequest = WebRequest.Create(url)
        Request.Credentials = CredentialCache.DefaultCredentials
        Return New StreamReader(Request.GetResponse().GetResponseStream()).ReadToEnd()
    Catch ex As Exception
        Return ""
    End Try

End Function
  • Worked ... ???

  • 1

    Excellent! Thanks @Virgilionovic for the clarity in the example and the layout!

2 answers

2


Install the package by Nuget: Newtonsoft.Json or via Package Manager:

PM> Install-Package Newtonsoft.Json

and write the following code to convert the text json for object Data

Class Date:

<Serializable()>
Public Class Data    
  Public Property Code As String    
  Public Property Codein As String    
  Public Property Name As String    
  Public Property High As Decimal    
  Public Property Low As Decimal    
  Public Property VarBid As Decimal    
  Public Property PctChange As Decimal    
  Public Property Bid As Decimal    
  Public Property Ask As Decimal    
  Public Property Timestamp As String    
  <Newtonsoft.Json.JsonProperty("create_date")>
  Public Property Createdate As Date
End Class

Conversion code:

Private Function GetData(ByVal json As String) As Data
    Dim items = Newtonsoft.Json.JsonConvert.DeserializeObject(Of List(Of Data))(json)
    Return items(0)
End Function

Final code:

 Dim json As String = GetWebPageText("https://economia.awesomeapi.com.br/usd-brl")
 Dim data As Data = GetData(json)
 Dim ask As Decimal = data.Ask

0

Resolved by adding the following line before making the call:

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls Or SecurityProtocolType.Tls11 Or SecurityProtocolType.Tls12

Browser other questions tagged

You are not signed in. Login or sign up in order to post.