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"}}


No comments:

Post a Comment