Thursday, September 13, 2018

Serialize .NET object to JSON

Let's say you have following classes:

Public Class Output
    Public Property Query As QueryDetails
End Class

Public Class QueryDetails
    Public Property Count As Integer
    Public Property Created As DateTime
    Public Property Lang As String
End Class

And let's also say you have created an object and have assigned values as such:

Dim MyQueryDetails As New QueryDetails With {.Count = 1, .Created = Now, .Lang = "en"}
Dim MyData As New Output
MyData.Query = MyQueryDetails

To "serialize" the object as JSON use the following code.  You will need to add a reference to the JSON.net library located at https://www.newtonsoft.com/json.

Dim Results As String = Newtonsoft.Json.JsonConvert.SerializeObject(MyData)
Console.WriteLine(Results)
'{"Query":{"Count":1,"Created":"2018-09-13T10:26:13.2004198-05:00","Lang":"en"}}


Wednesday, September 12, 2018

Call a REST API from .NET

To call a REST API using the "GET" ("POST" is beyond the scope of this article) HTTP verb, use the following code:

Using Client As New System.Net.WebClient

    Dim Results As String =
        Client.DownloadString("API URL")

End Using

This will populate the Results variable with the output of the web service call.  Almost invariably, this will be in the JSON format.  Note that all input is contained in query parameters in the API URL.

Now we need to get the JSON into a .NET object that can be easily read.  This process is called deserialization.  You can do this using native .NET classes, but oddly, Microsoft seems to prefer that you use the JSON.net library.  This can be downloaded at https://www.newtonsoft.com/json.

Next you will need to create a series of classes that correspond to the structure of the JSON output.  For example, if your output JSON looks like this:

{"query":{
    "count":1,
    "created":"2018-09-07T15:51:40Z",
    "lang":"en-US"
    }
}

You should create two classes like this:

Public Class Output
    Public Property Query As QueryDetails
End Class

Public Class QueryDetails
    Public Property Count As Integer
    Public Property Created As DateTime
    Public Property Lang As String
End Class

Then, simply write the following code to deserialize the JSON output into the .NET Output object:

Dim MyOutput As New Output
Newtonsoft.Json.JsonConvert.PopulateObject(Results, MyOutput)