Enrico Savegnago
Enrico Savegnago

Reputation: 3

Trying to parse JSON: Current JsonReader item is not an object

I already know to parse JSON in Java, but when I try to do it in VB.NET I get this error:

Newtonsoft.Json.JsonReaderException: 'Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.'*

This is the code:

    Dim requestUrl = "https://financialmodelingprep.com/api/v3/quote/TSLA?apikey={API_KEY}"

    Dim jsonCode As String = New WebClient().DownloadString(requestUrl)

    Dim json As JObject = JObject.Parse(jsonCode)
    Dim price = json.SelectToken("price")
    MsgBox(price)

End Sub

The message contained in the JSON is this:

[ {
  "symbol" : "TSLA",
  "name" : "Tesla, Inc.",
  "price" : 431.38000000,
  "changesPercentage" : 0.33000000,
  "change" : 1.43000000,
  "dayLow" : 427.76000000,
  "dayHigh" : 452.50000000,
  "yearHigh" : 502.49000000,
  "yearLow" : 65.42000000,
  "marketCap" : 408905547776.00000000,
  "priceAvg50" : 423.72656000,
  "priceAvg200" : 306.00583000,
  "volume" : 28554811,
  "avgVolume" : 63881259,
  "exchange" : "NASDAQ",
  "open" : 439.50000000,
  "previousClose" : 429.95000000,
  "eps" : 0.52300000,
  "pe" : 824.81836000,
  "earningsAnnouncement" : "2020-10-21T16:07:16.000+0000",
  "sharesOutstanding" : 947901033,
  "timestamp" : 1604951080
} ]

I would like to extract "price" and put it in a double.

Upvotes: 0

Views: 384

Answers (1)

David
David

Reputation: 6131

Since you know what the incoming payload looks like, you should go ahead and create a class to represent the object:

Public Class Quote

    Public Property symbol As String
    Public Property name As String
    Public Property price As Double
    Public Property changesPercentage As Double
    Public Property change As Double
    Public Property dayLow As Double
    Public Property dayHigh As Double
    Public Property yearLow As Double
    Public Property marketCap As Double
    Public Property priceAvg50 As Double
    Public Property priceAvg200 As Double
    Public Property volume As Double
    Public Property avgVolume As Double
    Public Property exchange As String
    Public Property open As Double
    Public Property previousClose As Double
    Public Property eps As Double
    Public Property pe As Double
    Public Property earningsAnnouncement As DateTimeOffset
    Public Property sharesOutstanding As UInteger
    Public Property timestamp As UInteger

End Class

From here you can use the DeserializeObject method to deserialize the array, get the first item in the collection, and then get the necessary properties:

Dim quotes = JsonConvert.DeserializeObject(Of List(Of Quote))(jsonCode)
Dim tesla = quotes?.SingleOrDefault()
If (tesla IsNot Nothing) Then
    Console.WriteLine(tesla.price)
End If

Upvotes: 1

Related Questions