How to iterate through all keys of json node

Mattia Fanti 356 Reputation points
2022-02-10T09:21:35.877+00:00

I'm trying to scrap the key values from This website API and it seems the json format it's not an array. I'm working with console .Net core 6.0 using System.Text.Json.Nodes

The code I'm using is :

 Dim streamData As Stream = Nothing
    Using http As HttpClient = New HttpClient
        Dim url As String = "https://api.hotbit.io/api/v1/market.status24h"

        Dim t As Task(Of Stream) = http.GetStreamAsync(url)
        streamData = t.Result
    End Using

    Dim jsonResponse As JsonNode = JsonNode.Parse(streamData)
    Dim jsonData As JsonNode = jsonResponse("result")

    Dim c As String = String.Empty

    For Each jsonCurrency As JsonNode In jsonData.AsObject
        c += jsonCurrency("last").ToString + " "
    Next

I took that code from StackOverFlow but that code is working great in that case because that Json contains arrays. In my case, this Json doesn't contain any array, so I'm getting the error:

Cannot convert type 'KeyValuePair(Of String, JsonNode)' in JsonNode

I want to parse and get all the values of the property "last".
Is there a way to make that code work in my case?
I'm trying to avoid to write all the properties because they are more than 1000 values

Thanks

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,555 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 111.5K Reputation points
    2022-02-10T13:14:43.573+00:00

    To get the values of "last" using your approach, try this fragment:

    Dim result As JsonObject = jsonResponse("result").AsObject
    
    For Each kvp In result.AsEnumerable
        c &= kvp.Value("last").ToString & ", "
    Next
    
    2 people found this answer helpful.

0 additional answers

Sort by: Most helpful