How to handle errors during Json parse?

Mattia Fanti 356 Reputation points
2022-02-15T00:26:51.767+00:00

I'm parsing Json and it could happen that a key is null, so I want to create an exception for a

NullReferenceException: Object Reference not set to an instance of an object

The code I'm using is:

Dim jsonResponse As JsonNode
               Using http As HttpClient = New HttpClient
                   Dim url As String = url 
                   jsonResponse = JsonNode.Parse(http.GetStreamAsync(url).Result)

               End Using

               Dim result = jsonResponse("result").AsObject
               Dim c As String = ""


               For Each kvp In result.AsEnumerable
                       Dim records = kvp.Value("records").AsArray
                       For Each r In records
                       Dim side As String = r("side").AsValue.ToString
                        next

Sometimes, the key "records" doesn't contain numbers, but it could be :null instead, so the software throw that error. How can I handle the error to keep running the code? Thanks

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,729 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jiachen Li-MSFT 31,801 Reputation points Microsoft Vendor
    2022-02-15T02:14:59.737+00:00

    Hi @Mattia Fanti ,
    You can prevent this exception by adding predicates in front.

                If kvp.Value("records") IsNot Nothing Then  
                    Dim records = kvp.Value("records").AsArray  
                    For Each r In records  
                        Dim side As String = r("side").AsValue.ToString  
                    Next  
                End If  
    

    Or use the Try Catch statement to handle this exception.

                Try  
                    Dim records = kvp.Value("records").AsArray  
                    For Each r In records  
                        Dim side As String = r("side").AsValue.ToString  
                    Next  
                Catch ex As System.NullReferenceException  
                Console.WriteLine(ex.Message)  
                End Try  
    

    Hope this could be helpful.
    Best Regards.
    Jiachen Li

    ----------

    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.