Starlays Starlays - 2 years ago 76 Question

Deserializing null value in JSON

I need some help in JSON desereialization of null value, there is an error in the output window but I don't know what is the cause, the error is:

Exception thrown: 'Newtonsoft.Json.JsonSerializationException' in Newtonsoft.Json.dll

The JSON looks like this:


The portion of the code that is handling the deserialize looks like this:

Dim responsebody = (New Text.UTF8Encoding).GetString(responsebytes)
'Dim settings = New JsonSerializerSettings()
'settings.NullValueHandling = NullValueHandling.Include
'settings.MissingMemberHandling = MissingMemberHandling.Ignore
'settings.DateParseHandling = DateParseHandling.None
Dim datacollection = JsonConvert.DeserializeObject(Of jsonPrjData())(responsebody)

For Each oneVar As jsonPrjData In datacollection
' Avoid Nothing vars.
If oneVar IsNot Nothing Then
datagrid.Rows.Add(oneVar.TID, oneVar.taskDescript, oneVar.taskStatus, oneVar.prjDescript, oneVar.username, oneVar.dateUserAccept.ToString("dd-MM-yyyy"), oneVar.estimatedDuration, oneVar.actualDuration)
End If
Public Class jsonPrjData
Public Property TID() As Int16
Public Property taskDescript() As String
Public Property taskStatus() As Int16
Public Property username() As String
Public Property prjDescript() As String
Public Property dateUserAccept() As Date
Public Property estimatedDuration() As Int16
Public Property actualDuration() As Int16
End Class

The line with
doesn't return nothing, because of the error when desearializing null value. How can I solve the problem?

Answer Source

Using this property in your class:

Public Property dateuseraccept As DateTime?

DateTime? or Nullable(of DateTime) seems to be needed here since in that json, dateuseraccept is null. This allows the variable to store null/Nothing or a valid datetime.

Since your error comes from Newtonsoft.Json.dll and the code involving Json is your DeserializeObject, it is likely the same source.

Then use HasValue to determine when a Nullable(Of T) is Nothing:

If item.dateuseraccept.HasValue Then
    Console.WriteLine("No Date")
End If

It may not be the only thing wrong, but it works fine for me with that.

Nullable(Of T)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download