使用 Json.NET 从 VB.NET 中的 JSON 获取信息
Posted
技术标签:
【中文标题】使用 Json.NET 从 VB.NET 中的 JSON 获取信息【英文标题】:Getting info from JSON in VB.NET using Json.NET 【发布时间】:2022-01-18 16:45:57 【问题描述】:我需要处理这个 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
我不知道这是否是最佳方式,但它正在工作......
【问题讨论】:
【参考方案1】: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
【讨论】:
以上是关于使用 Json.NET 从 VB.NET 中的 JSON 获取信息的主要内容,如果未能解决你的问题,请参考以下文章
从 vb.net 中的模式窗口调用 javascript 函数