Search code examples
vb.netjson-deserializationjsonconvert

VB.NET, keywords as variable names


I have to deserialize some json data string into structure. Problem is that data names conflicts vith VB keywords what is in C# not a case.

This is json string:

{"id":2526068,"date":"2019-07-21T19:15:17.4468196+02:00","error":""}

Problematic names are obviously "date" and "error". Somewhere I found that such variables should be surrended with []. But this don't work for me.
Here is my code:

Structure reqjson
    Dim id As String
    Dim [date] As String
    Dim [error] As String
End Structure

Dim idnum As Long = 0
Dim sldate As String = ""
If Not String.IsNullOrEmpty(jsonstr) Then
        Dim r As reqjson = JsonConvert.DeserializeObject(Of reqjson)(jsonstr)
        idnum = CLng(r.id)
        sladate = r.date.ToString("dd.MM.yyyy. hh:mm:ss.fff")
End If

Problem is that deserializer can't deserialize data if they don't have a same name what VB don't allow. In C# this declaration is legal:

struct reqjson{
string id;
string date;
string error;
};

But not in VB.NET. What to do here?


Solution

  • I don't see any problem with your deserialization. Your code works for me!

    But perhaps you should address a couple potential issues. Don't use Dim for class level fields. Use Public or Private

    Structure reqjson
        Public id As String
        Public [date] As String
        Public [error] As String
    End Structure
    

    And I'm not changing anything here, other than adding the json string myself

    Public Shared Sub foo()
        Dim jsonstr = "{""id"":2526068,""Date"":""2019-07-21T19:15:17.4468196+02:00"",""error"":""""}"
        Dim idnum As Long = 0
        Dim sldate As String = ""
        If Not String.IsNullOrEmpty(jsonstr) Then
            Dim r As reqjson = JsonConvert.DeserializeObject(Of reqjson)(jsonstr)
            idnum = CLng(r.id)
    

    However, you are doing String.ToString(). Try this instead

            sldate = Date.Parse(r.date).ToString("dd.MM.yyyy. hh:mm:ss.fff")
        End If
    End Sub
    

    Or better yet, use an actual date in the struct

    Structure reqjson
        Public id As String
        Public [date] As Date
        Public [error] As String
    End Structure
    

    which makes your original code work

    sldate = r.date.ToString("dd.MM.yyyy. hh:mm:ss.fff")