I have the following functions.
When I callgetQueryObject(jsonString)
It makes the coll parses the object then returns.
The the assignment to jsonObject
is not working. When I start operating on the jsonObject
bariable it has the value nothing.
I run Deb开发者_开发百科ug and follow the code and the jsonObject
in getQueryObject
is not failing. and return says it returns the object.
I am new to VB is there something I am missing?
Public Function getInformation(jsonString as string) as string
Dim jsonObject As JObject
jsonObject = getQueryObject(jsonString)
'Operate on object here.
End Function
Private Function getQueryObject(jsonString as string) As JObject
Dim jsonObject As JObject
Try
jsonObject = JObject.Parse(jsonString)
Catch ex As Exception
jsonObject = New JObject
End Try
Return jsonObject
End Function
A little more information. After I turned on Option strict I started to get an error. Option Strict On disallows implicit conversions from 'Newtonsoft.Jsont.Linq.Token to Newtonsoft.Json.Linq.JObject'.
I don's see where I am making any type of conversion.
The problem is that you've used in the incorrect variable name in the getInformation
function.
Change your code to look like this, instead:
Public Function GetInformation(jsonString as string) as string
Dim jsonObj As JObject
jsonObj = GetQueryObject(jsonString) // Change the name of this variable
// to match the declaration above it.
'Operate on object here.
End Function
Or even simpler, declare and initialize the variable in the same line:
Public Function GetInformation(jsonString as string) as string
Dim jsonObj As JObject = GetQueryObject(jsonString)
'Operate on object here.
End Function
If you were compiling your code with Option Explicit
and Option Strict
both turned on, the compiler would have caught this problem for you. Change those settings in your project's Properties. NEVER write code in VB.NET with Option Explicit
turned off. Unexpected things happen.
What's happening is that VB.NET is letting you use the jsonObject
variable without ever declaring it. The compiler just automagically initializes it to Nothing
behind the scenes, which is the default value. It's a simple enough mistake to make, since that's the name of the variable in the other method. But it doesn't work as expected, because it's not the name of the variable in this method. As long as you haveOption Explicit
off, VB.NET doesn't warn you, and blissfully compiles wrong code.
(Note that I'm also following the recommended .NET coding convention of CamelCasing all method names. That means they should start with a capital letter, rather than a lower-case letter. Only local variables and parameters should be pascalCased (initial lower-case).)
Public Function getInformation(jsonString as string) as string
Dim jsonObj As JObject
jsonObject = getQueryObject(jsonString)
'Operate on object here.
End Function
Is jsonObject declared globally?
精彩评论