Eminem Eminem - 2 years ago 120
Vb.net Question

What is the VB.Net equavilent of the following

I need to convert the following to VB.Net. I tried the online converter and the conversion gives an error

var result = JsonConvert.DeserializeObject<T>(parsed["result"].ToString(),
new JsonSerializerSettings
{
/*
* Because Aliexpress Api logic is very weird -
* it could return "-" for totalResults field,
* Which is Integer by documentation and common sense
*/
Error = HandleDeserializationError
});

protected void HandleDeserializationError(object sender, ErrorEventArgs errorArgs)
{
var currentError = errorArgs.ErrorContext.Error.Message;
errorArgs.ErrorContext.Handled = true;
}


The converted code gives

Dim result = JsonConvert.DeserializeObject(Of T)(parsed("result").ToString(), New JsonSerializerSettings() With { _
Key .[Error] = HandleDeserializationError _
})

Protected Sub HandleDeserializationError(sender As Object, errorArgs As ErrorEventArgs)
Dim currentError = errorArgs.ErrorContext.[Error].Message
errorArgs.ErrorContext.Handled = True
End Sub


The ErrorEventArgs class is defined as

Public Class ErrorEventArgs
Inherits EventArgs

Public Sub New(currentObject As Object, errorContext As ErrorContext)

Public ReadOnly Property CurrentObject As Object
Public ReadOnly Property ErrorContext As ErrorContext
End Class


Basically I have the converted procedure:

Protected Sub HandleDeserializationError(sender As Object, errorArgs As ErrorEventArgs)
Dim currentError As String = errorArgs.ErrorContext.[Error].Message
errorArgs.ErrorContext.Handled = True
End Sub


And I need to assign it as an event handler

Something like

Dim s As JsonSerializerSettings = New JsonSerializerSettings()
s.Error = HandleDeserializationError()
Dim result = JsonConvert.DeserializeObject(Of T)(parsed("result").ToString(), s)

Answer Source

Very similar to the generated code, but there are some changes. I don't know what the generator was doing with Key, and I don't think it's necessary to bracket the Error keyword in this context.

Dim Result = JsonConvert.DeserializeObject(OF T)(parsed("result").ToString(), _
                New JsonSerializerSettings With { .Error = AddressOf HandleDeserializationError} )


Protected Sub HandleDeserializationError(sender As Object, ErrorArgs As EventArgs)
    'The first line in this method didn't do anything
    errorArgs.ErrorContext.Handled = True
End Sub
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download