我需要處理這個 JSON:
{
"companies": [
{
"companyId": "S86jhs89F",
"companyName": "LoremIpsum"
}
],
"response_metadata": {
"next_cursor": 659,
"next_link": "somedata"
} }
如何使用 VB.NET 獲取 companyId、companyName、next_cursor 和 next_link?
更新...
我找到了這個...
Dim json As String = "{ ... textJSON ... }"
Dim ser As JObject = JObject.Parse(json)
Dim data As List(Of JToken) = ser.Children().ToList
Dim output As String = ""
For Each grupo As JProperty In data
grupo.CreateReader()
Select Case grupo.Name
Case "companies"
For Each item As JObject In grupo.Values
output = vbCrLf " -- " item("companyId").ToString
output = vbCrLf " -- " item("companyName").ToString
Next
Case "response_metadata"
Dim dato As JObject = grupo.Value
output = vbCrLf " -- " dato("next_cursor").ToString
End Select
Next
我不知道這是否是最佳方式,但它正在起作用......
uj5u.com熱心網友回復:
Visual Studio 有一個很酷的功能,稱為將 JSON 粘貼為類,可以在“編輯”>“選擇性粘貼”>“將 JSON 粘貼為類”下找到。如果你這樣做,那么你會得到如下所示的內容:
Public Class Rootobject
Public Property companies() As Company
Public Property response_metadata As Response_Metadata
End Class
Public Class Response_Metadata
Public Property next_cursor As Integer
Public Property next_link As String
End Class
Public Class Company
Public Property companyId As String
Public Property companyName As String
End Class
如果需要,您可以使用裝飾器使屬性名稱更符合 .NET 風格:
Public Class Rootobject
<JsonProperty("companies")>
Public Property Companies As IEnumerable(Of Company)
<JsonProperty("response_metadata")>
Public Property ResponseMetadata As Response_Metadata
End Class
Public Class Response_Metadata
<JsonProperty("next_cursor")>
Public Property NextCursor As Integer
<JsonProperty("next_link")>
Public Property NextLink As String
End Class
Public Class Company
<JsonProperty("companyId")>
Public Property CompanyId As String
<JsonProperty("companyName")>
Public Property CompanyName As String
End Class
現在您將使用 JsonConvert.DeserializeObject 將 JSON 文字轉換為您的根物件。之后,只需獲取所需的屬性即可:
Dim conversion = JsonConvert.DeserializeObject(Of Rootobject)(literal)
Dim companyId = conversion.Companies.First().CompanyId
Dim companyName = conversion.Companies.First().CompanyName
' etc.
示例:https : //dotnetfiddle.net/GiGKwI
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/384926.html
