使用 Json.NET 从 VB.NET 中的 JSON 获取信息

Getting info from JSON in VB.NET using Json.NET

我需要处理这个 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

我不知道这是否是最佳方式,但它确实有效...

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