Search code examples
jsonvb.netserializationjavascriptserializer

Iterate Object Deserialized JSON


I cannot figure out how to iterate through an object to retrieve a list of errors sent in a JSON string. I have a For Each loop looing at each key pair value in my JSON but the third key pair is an object of key pairs. I cannot access these using the same For Each structure (I can access them if I loop through the object but want to keep it consistent if possible.. My 'Case Is "Errors" case statement is where I want to iterate the errors object but I am not sure how to get to it.. Here is my code.. I hope someone can assist..

Sample JSON:

{"success":"true","api_reference":3821,"errors":[{"record":"landlord","record_id":"-16::1::LPMB40-2385DDDC","error":"Please ensure the email field has been completed","error_code":"33101"},{"record":"landlord","record_id":"-16::1::LPMB40-2385DDDC","error":"Please ensure the email field is a valid email address","error_code":"33102"}]}

                Dim jss = New JavaScriptSerializer()
            Dim data = jss.Deserialize(Of Object)(responseFromServer)
            Dim strSuccess = "", strAPIReference = ""
            Dim intExpiresIn = 0
            Dim ErrorsObject As Object

            For Each kvp As KeyValuePair(Of String, Object) In data

                Select Case kvp.Key

                    Case Is = "success"

                        strSuccess = kvp.Value

                    Case Is = "api_reference"

                        strAPIReference = kvp.Value

                    Case Is = "errors"

                        ErrorsObject = kvp.Value

                        For Each errorskvp As KeyValuePair(Of String, Object) In ErrorsObject


                        Next

                End Select

            Next

Solution

  • I would suggest doing this strongly typed, so that you can deserialize the json to a real object and use the object properties. That way it's much easier to read the values and loop errors etc:

    Classes:

    Public Class JsonResponse
        Public Property Success As Boolean
        Public Property Api_reference As String
    
        Public Property Errors As IEnumerable(Of JsonError)
    End Class
    
    Public Class JsonError
        Public Property Record As String
        Public Property Record_Id As String
        Public Property [Error] As String
        Public Property Error_Code As String
    End Class
    

    Deserialization and use:

    Dim j As New JavaScriptSerializer()
    
    Dim data As JsonResponse = j.Deserialize(Of JsonResponse)(responseFromServer)
    
    If Not data.Success Then
        For Each myError As JsonError In data.Errors
    
        Next
    End If