我試圖從這個網站API中洗掉鍵值,它似乎是 json 格式,它不是一個陣列。我正在使用 System.Text.Json.Nodes 使用控制臺 .Net core 6.0
我正在使用的代碼是:
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
但我得到了錯誤:
無法在 JsonNode 中轉換型別 'KeyValuePair(Of String, JsonNode)'
我究竟做錯了什么?謝謝
uj5u.com熱心網友回復:
創建一個類來表示您的 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 的最后一個值,而無需手動輸入每個值。你可以做的是:
- 使用反射獲取 Result 類的每個屬性
- 回圈遍歷集合
- 使用 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
小提琴:https ://dotnetfiddle.net/USAAgc
uj5u.com熱心網友回復:
我解決了使用
Dim result As JsonObject = jsonResponse("result").AsObject
For Each kvp In result.AsEnumerable
c &= kvp.Value("last").ToString & ", "
Next
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/426216.html
標籤:json VB.net .net-core 控制台应用程序
上一篇:如何在VisualBasic(VisualStudio)中向DataGridView添加行
下一篇:在變數中傳遞和存盤可選委托
