Avatar of hankknight
hankknight
Flag 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?
Visual Basic.NETASP.NET

Avatar of undefined
Last Comment
kaufmed

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
kaufmed

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy