Deserialize JSON keep getting null referance exception

295 views Asked by At

Okay, so I want to deserialize the json from https://openrct.net/ajax/chat.php. Problem is that no matter what I try, I end up with a Null Reference Exception when I try to access the stored data. I have been trying for close to an hour, googling and trying different things, and I am completely at a loss for how to do this. Please help me out.

Imports Newtonsoft
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Imports System.Net
Public Class Form1
Dim WS As New WebClient

'/ajax/chat.php
'And /ajax/chat.php?latest=55 to get all chat messages after that ID
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

End Sub
Public Class PostWrapper
    Public posts() As Post
End Class

Public Class Post
    Public Property a() As String
    Public Property m() As String
    Public Property t() As String
End Class

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim json As String = WS.DownloadString("https://openrct.net/ajax/chat.php")
    MsgBox(json)
    Dim postWrapper = JsonConvert.DeserializeObject(Of PostWrapper)(json) ' Deserialize array of Post objects
    MsgBox(postWrapper.posts(0).m) 'Errors Here.
End Sub
End Class

Thank you.

2

There are 2 answers

1
Okan Kocyigit On BEST ANSWER

Your object classes for deserializing are wrong, you can use jsonutils.com for generating classes from json string or URL.

Here is the classes for your json,

Public Class M
    Public Property id As String
    Public Property a As String
    Public Property m As String
    Public Property t As String
End Class

Public Class Example
    Public Property m As M()
    Public Property l As String
End Class

Dim postWrapper = JsonConvert.DeserializeObject(Of Example)(json)
MsgBox(postWrapper.m)
3
Sagar Koshti On

I am not .Net developer but what i can suggest is you should check for authentication details while calling for this link as its https, which means its secured line so it may be refusing your connection. Link