Serialize JSON (convert a class to a string)

This is a short piece of code that will Deserialize a JSON document in string form into a class

 

Imports System.IO
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Json
 
Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
        'instantiate the test class
        Dim oItem As New Item
        'populate the properties
        oItem.ItemName = "my item name"
        oItem.ItemNumber = "1001"
 
        'create a memory stream
        Dim ms As New MemoryStream
        'create a DataContractJsonSerializer based on the Item class
        Dim ser As New DataContractJsonSerializer(GetType(Item))
        'write the oItem object to the mem stream
        ser.WriteObject(ms, oItem)
        ms.Position = 0
        'read the mem stream into a stream reader
        Dim sr As New StreamReader(ms)
        'read the stream reader into a string
        Dim strJSON As String = sr.ReadToEnd
 
        Stop
        'resulting JSON:
 
        '{
        '    "ItemName": "my item name",
        '    "ItemNumber": "1001"
        '}
 
    End Sub
End Class
 
<DataContract>
Class Item
    <DataMember>
    Public ItemNumber As String
    <DataMember>
    Public ItemName As String
End Class

RealWorldCode gives developers practical, real‑world solutions with clean, working code — no fluff, no theory, just answers.
Links
Home
Knowledge Areas
Sitemap
Contact
Et cetera
Privacy Policy
Terms and Conditions
Cookie Preferences