I have a bunch of JSON objects that I'm reading in via REST. They follow a format like this:
{
"Id": 13,
"ParentId": 21,
"Description": "This is the description"
"Errors": []
}
I'm creating a class from the returned JSON object. In this example, the class would look like this:
Public Class ReturnedInfo
Public Id As Integer
Public ParentId As Integer
Public Description As String
Public Errors As ErrorDetail()
End Class
Then I'm pulling in the data like this:
Private Function GetReturnedInfo(myID As Integer, tkn As String) As ReturnedInfo
Dim rval As ReturnedInfo = New ReturnedInfo()
Try
'set up request
Dim url As String = "https://www.exampleurl.com"
Dim request As HttpWebRequest = CType(WebRequest.Create(url), HttpWebRequest)
request.Method = "POST"
request.ContentType = "application/json"
'add logon data to the request stream
Dim dataStream As Stream = request.GetRequestStream()
Using writer As New StreamWriter(dataStream)
writer.Write("{""Username"":""MyUserName"", ""Company"":""1234-56789-123"",""SecurityToken"":""" + tkn + """, ""ID"":""" + myID + """}")
End Using
dataStream.Close()
'run the request and collect the response
Dim ws As WebResponse = request.GetResponse()
Dim rs As System.IO.Stream = ws.GetResponseStream()
Dim jsonString As String = String.Empty
Using sreader As System.IO.StreamReader = New System.IO.StreamReader(rs)
jsonString = sreader.ReadToEnd()
End Using
'pull data from the response and convert it to a ReturnedInfo
Dim jsSerializer As System.Web.Script.Serialization.JavaScriptSerializer = New System.Web.Script.Serialization.JavaScriptSerializer()
Dim retInfo As ReturnedInfo = jsSerializer.Deserialize(Of ReturnedInfo)(jsonString)
'If the security token is expired, get a new one and re-call function
If retInfo.Errors.Length > 0 Then
If retInfo.Errors(0).Code = "Validation Error" Then
token = GetSecurityToken()
rval = GetReturnedInfo(myID, token.SecurityToken)
End If
Else
rval = retInfo
End If
Catch wex As WebException
'exceptions from the server are communicated with a 4xx status code
Dim errorMsg As String = HandleWebException(wex)
Throw New System.Exception(errorMsg)
Catch ex As Exception
'TODO: open dialog box and display ex
Throw New System.Exception("Hit exception: " & ex.Message)
End Try
Return rval
End Function
This logic has worked perfectly for me until I ran into a returned JSON object that looks like this:
{
"$id": 10
"Id": 13,
"ParentId": 21,
"Description": "This is the description"
"Errors": []
}
Since VB.NET won't let me declare a variable that starts with a $
I'm kind of stuck. How do I either force VB.NET to like the $
or find another way around this?
Thanks!