Json in Visual Basic .NET

Imports System
Imports System.Text.Json
Imports System.Text.Json.Serialization

' We'll use these two classes to demonstrate encoding and
' decoding of custom types below.
Public Class Response1
    Public Property Page As Integer
    Public Property Fruits As String()
End Class

' Only public properties will be serialized/deserialized in JSON.
' We can use attributes to customize the JSON property names.
Public Class Response2
    <JsonPropertyName("page")>
    Public Property Page As Integer

    <JsonPropertyName("fruits")>
    Public Property Fruits As String()
End Class

Module JSONExample
    Sub Main()
        ' First we'll look at encoding basic data types to
        ' JSON strings. Here are some examples for atomic values.
        Console.WriteLine(JsonSerializer.Serialize(True))
        Console.WriteLine(JsonSerializer.Serialize(1))
        Console.WriteLine(JsonSerializer.Serialize(2.34))
        Console.WriteLine(JsonSerializer.Serialize("gopher"))

        ' And here are some for arrays and dictionaries, which encode
        ' to JSON arrays and objects as you'd expect.
        Dim slcD As String() = {"apple", "peach", "pear"}
        Console.WriteLine(JsonSerializer.Serialize(slcD))

        Dim mapD As New Dictionary(Of String, Integer) From {
            {"apple", 5},
            {"lettuce", 7}
        }
        Console.WriteLine(JsonSerializer.Serialize(mapD))

        ' The JSON package can automatically encode your
        ' custom data types.
        Dim res1D As New Response1 With {
            .Page = 1,
            .Fruits = New String() {"apple", "peach", "pear"}
        }
        Console.WriteLine(JsonSerializer.Serialize(res1D))

        ' You can use attributes on class properties
        ' to customize the encoded JSON property names. Check the
        ' definition of `Response2` above to see an example
        ' of such attributes.
        Dim res2D As New Response2 With {
            .Page = 1,
            .Fruits = New String() {"apple", "peach", "pear"}
        }
        Console.WriteLine(JsonSerializer.Serialize(res2D))

        ' Now let's look at decoding JSON data into .NET
        ' values. Here's an example for a generic data structure.
        Dim jsonString As String = "{""num"":6.13,""strs"":[""a"",""b""]}"

        ' We need to provide a type where the JSON
        ' package can put the decoded data. This
        ' Dictionary(Of String, Object) will hold a dictionary of strings
        ' to arbitrary data types.
        Dim dat As Dictionary(Of String, Object) = 
            JsonSerializer.Deserialize(Of Dictionary(Of String, Object))(jsonString)
        Console.WriteLine(String.Join(", ", dat.Select(Function(kvp) $"{kvp.Key}: {kvp.Value}")))

        ' In order to use the values in the decoded dictionary,
        ' we'll need to convert them to their appropriate type.
        ' For example here we convert the value in `num` to
        ' the expected `Double` type.
        Dim num As Double = Convert.ToDouble(dat("num"))
        Console.WriteLine(num)

        ' Accessing nested data requires a series of conversions.
        Dim strs As Object() = CType(dat("strs"), Object())
        Dim str1 As String = CStr(strs(0))
        Console.WriteLine(str1)

        ' We can also decode JSON into custom data types.
        ' This has the advantages of adding additional
        ' type-safety to our programs and eliminating the
        ' need for type conversions when accessing the decoded data.
        Dim str As String = "{""page"": 1, ""fruits"": [""apple"", ""peach""]}"
        Dim res As Response2 = JsonSerializer.Deserialize(Of Response2)(str)
        Console.WriteLine($"Page: {res.Page}, Fruits: {String.Join(", ", res.Fruits)}")
        Console.WriteLine(res.Fruits(0))

        ' In the examples above we always used strings as
        ' intermediates between the data and JSON representation.
        ' We can also stream JSON encodings directly to TextWriter
        ' objects like Console.Out.
        Dim d As New Dictionary(Of String, Integer) From {
            {"apple", 5},
            {"lettuce", 7}
        }
        JsonSerializer.Serialize(Console.Out, d)
    End Sub
End Module

This Visual Basic .NET code demonstrates JSON encoding and decoding using the System.Text.Json namespace, which is the modern way to handle JSON in .NET.

The code shows how to:

  1. Serialize basic data types to JSON
  2. Serialize arrays and dictionaries to JSON
  3. Define custom classes and serialize them to JSON
  4. Use attributes to customize JSON property names
  5. Deserialize JSON into generic Dictionary(Of String, Object)
  6. Access and convert values from deserialized JSON
  7. Deserialize JSON into custom classes
  8. Stream JSON directly to output

Note that Visual Basic .NET uses different syntax and conventions compared to Go:

  • Classes are used instead of structs
  • Properties are used instead of fields
  • Attributes are used for metadata instead of struct tags
  • The JsonSerializer class is used for both serialization and deserialization
  • Dictionary(Of TKey, TValue) is used instead of map
  • Arrays are used instead of slices

When running this program, you’ll see similar output to the Go version, demonstrating the JSON encoding and decoding capabilities in Visual Basic .NET.