Search code examples
.netjsonvb.netjavascriptserializer

VB.Net Getting Value from JSON


Please could someone help me get the branch_id in each branch from this JSON?

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

I am using JavaScriptSerialiser to deserialize the JSON but am not doing it properly as I think the JSON is not an array like I have used before:

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

Solution

  • Declare a Branch class and add a property branches As Dictionary(Of String, Branch) to your OfficeCheckJsonResponse class.

    Using JavaScriptSerialiser, deserialise the JSON into an instance of OfficeCheckJsonResponse.

    You can get your branch_id values by iterating over data.branches. You could alternatively use 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