VB.Net 从 JSON 中获取价值

VB.Net Getting Value from JSON

有人可以帮我从这个 JSON 的每个分支中获取 branch_id 吗?

{
    "branches": {
        "1": {
            "member_id": "-16",
            "branch_id": "1"
        },
        "2": {
            "member_id": "-16",
            "branch_id": "1"
        }
    }
}

我正在使用 JavaScriptSerialiser 来反序列化 JSON,但我没有正确执行它,因为我认为 JSON 不是我之前使用的数组:

 Dim jss As New JavaScriptSerializer()
        Dim data As OfficeCheckJsonResponse = jss.Deserialize(Of OfficeCheckJsonResponse)(responseFromServer)

使用 Newtonsoft,对象类型是字典(整数,样本 Class),就像在同一主题中一样,检查 link Go This Link

    Dim JsonSettings = New Newtonsoft.Json.JsonSerializerSettings
    JsonSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore
    Dim OutObject = Newtonsoft.Json.JsonConvert.DeserializeObject(Of branch)("###JSONSTRING###")
    Public Class branch
        Property branches As Dictionary(Of Integer, SampleClass)
        Class SampleClass
            Property member_id As String
            Property branch_id As String
        End Class
    End Class

Class 在 Value 属性 内并且 Key 是唯一字符串,如本例中的 1,2,3,4 ...

         For Each DictionaryElement As KeyValuePair(Of String, BranchesData) In branches
            Debug.Print(DictionaryElement.Key) 'Is Key 1,2,3 etc..
            'DictionaryElement.Value is BranchesData
            Debug.Print(DictionaryElement.Value.branch_id)
            Debug.Print(DictionaryElement.Value.member_id)
        Next

声明一个 Branch class 并添加一个 属性 branches As Dictionary(Of String, Branch) 到你的 OfficeCheckJsonResponse class.

使用 JavaScriptSerialiser,将 JSON 反序列化为 OfficeCheckJsonResponse 的实例。

您可以通过遍历 data.branches 获得 branch_id 值。您也可以使用 LINQ。

Sub Main
    Dim responseFromServer = "{
    ""branches"":  {
        ""1"": {
            ""member_id"": ""-16"",
            ""branch_id"": ""1""
        },
        ""2"": {
            ""member_id"": ""-16"",
            ""branch_id"": ""1""
        }
    }
}"

    Dim jss As New JavaScriptSerializer()
    Dim data As OfficeCheckJsonResponse =
        jss.Deserialize(Of OfficeCheckJsonResponse)(responseFromServer)

    For Each branch As KeyValuePair(Of String, Branch) In data.branches
        Console.WriteLine(Int32.Parse(branch.Key))
        Console.WriteLine(branch.Value)
    Next
End Sub

Public Class OfficeCheckJsonResponse
    Public Property branches As Dictionary(Of String, Branch)
End Class

Public Class Branch
    Property member_id As String
    Property branch_id As String
End Class