如何遍历 json 节点的所有键

How to iterate through all keys of json node

我正试图从该网站 API 中删除键值,json 格式似乎不是数组。 我正在使用控制台 .Net 核心 6.0 使用 System.Text.Json.Nodes

我使用的代码是:

    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

但我收到错误消息:

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

我做错了什么? 谢谢

创建一个 class 来代表您的 JSON,像这样:

Public Class MarketStatus
    Public Property IsChange As Boolean
    Public Property period As Integer
    Public Property open As String
    Public Property last As String
    Public Property high As String
    Public Property low As String
    Public Property volume As String
    Public Property deal As String
    Public Property close As String
    Public Property base_volume As String
    Public Property quote_volume As String
End Class

Public Class Payload
    Public Property _error As Object
    Public Property result As Result
    Public Property id As Integer
End Class

Public Class Result

    <JsonPropertyName("0xBTCBTC")>
    Public Property _0xBTCBTC As MarketStatus

    <JsonPropertyName("0xBTCETH")>
    Public Property _0xBTCETH As MarketStatus

    <JsonPropertyName("0xCASHUSDT")>
    Public Property _0xCASHUSDT As MarketStatus

    <JsonPropertyName("1INCH1D3LUSDT")>
    Public Property _1INCH1D3LUSDT As MarketStatus

    ' etc...
End Class

现在您可以使用 JsonSerializer.Deserialize 或 JsonSerializer.DeserializeAsync:

反序列化整个负载
Dim payloadObject = Await JsonSerializer.DeserializeAsync(Of Payload)(streamData)

更新

根据我们在此答案的评论中的对话,您希望获得每个 MarketStatus 的最后一个值,而不必手动输入每个值。您可以做的是:

  1. 使用反射获取每个 属性 的 Result class
  2. 遍历集合
  3. 使用PropertyInfo.GetValue获取反序列化对象的值

下面是一个使用与上面相同的变量名的例子:

For Each propertyInformation In GetType(Result).GetProperties()
    Dim status = DirectCast(propertyInformation.GetValue(payloadObject.result), MarketStatus)
    Console.WriteLine("{0}.last = {1}", propertyInformation.Name, status.last)
Next

Fiddle: https://dotnetfiddle.net/USaAgc

我用

解决了
 Dim result As JsonObject = jsonResponse("result").AsObject
    
 For Each kvp In result.AsEnumerable
     c &= kvp.Value("last").ToString & ", "
 Next