Link to home
Start Free TrialLog in
Avatar of hankknight
hankknightFlag for Canada

asked on

ASP.NET/VB: JavaScriptSerializer - Avoiding Errors When JSON Empty

This works:
Imports System.Web.Script.Serialization
Public Class JSONstuff
    Inherits System.Web.UI.Page
    Dim obj As ResultRows
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim data As String = "{""total_rows"":427,""offset"":0,""rows"":[ {""id"":""123xyz""} ]}"
        Dim jsd As New JavaScriptSerializer
        obj = jsd.Deserialize(Of ResultRows)(data)
        Response.Write("id: " & obj.rows(0).id)
    End Sub
End Class

Public Class ResultRows
    Public rows() As ResultRow
End Class

Public Class ResultRow
    Public id As String
End Class

Open in new window

But this returns an error:

Server Error in '/' Application.
Index was outside the bounds of the array.
Imports System.Web.Script.Serialization
Public Class JSONstuff
    Inherits System.Web.UI.Page
    Dim obj As ResultRows
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim data As String = "{""total_rows"":427,""offset"":0,""rows"":[]}"
        Dim jsd As New JavaScriptSerializer
        obj = jsd.Deserialize(Of ResultRows)(data)
        Response.Write("id: " & obj.rows(0).id)
    End Sub
End Class

Public Class ResultRows
    Public rows() As ResultRow
End Class

Public Class ResultRow
    Public id As String
End Class

Open in new window

Instead of returning an error, how can I get it to return an empty value for the id?
ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial