ali ali - 1 year ago 47 Question

Value cannot be null from JsonSoft in VB.NET

I have the following JSON content:

"name": "alex",
"age": 23,
"codes": {
"1233": 1.2,
"1234": 2,
"1443": 2.4

In VB.NET, I get the values into variables like this:

Dim o As JObject = JObject.Parse(jsonContent)

Dim name as String = o.SelectToken("name");
Dim age as Integer = o.SelectToken("age");
Dim codes as JObject = o.SelectToken("codes");

I can see that name and age are correctly parsed but if I want to get the value of a code from
, I get an error about the value being null (what value, I don't know)

Dim code As Double = codes.SelectToken("1234")
' An unhandled exception of type 'System.ArgumentNullException' occurred
' in Newtonsoft.Json.dll
' Additional information: Value cannot be null

In the Autos window I see that the value of codes is
{{ "1233": 1.2, "1234": 2, "1443": 2.5 }}

What am I doing wrong?

Answer Source

Your code will not compile using Option Strict.

Dim codes As JObject = jobj.SelectToken("codes")
Dim code As Double = codes.SelectToken("1234")

SelectToken returns a JToken which inherits from System.Object which is different than a JObject. The same for the Double implicit cast. This works:

Dim jobj = JObject.Parse(jstr)




For typed variables:

Dim name As String = jobj("name").ToString()
Dim codes = jobj("codes")

' .Item is optional
Dim a As Double = Convert.ToDouble(codes("1233"))
Dim b As Double = Convert.ToDouble(codes.Item("1234"))
Dim c As Double = Convert.ToDouble(codes.Item("1443"))

Of course, if you are consuming each element in it, you probably should consider deserializing it.