Need help with your JSON?

Try our JSON Formatter tool to automatically identify and fix syntax errors in your JSON. JSON Formatter tool

Visual Basic .NET JSON Formatting

Why Format JSON in VB.NET?

Working with JSON (JavaScript Object Notation) is a common task in modern software development, especially when dealing with web services, APIs, and configuration files. In Visual Basic .NET, you'll frequently need to serialize .NET objects into JSON strings or deserialize JSON strings into .NET objects. Beyond simple conversion, controlling the *format* of the output JSON is crucial for various reasons:

  • Readability: Pretty-printing (indenting and adding line breaks) makes JSON easier for humans to read and debug. This is vital during development and testing.
  • Compactness: Removing unnecessary whitespace (minifying) reduces the size of the JSON string. This is important for performance, especially when transferring data over networks, saving storage space, or for configuration files where size matters.
  • Consistency: Ensuring consistent formatting across your application improves code maintainability and reduces merge conflicts when multiple developers work on JSON-related code.

Visual Basic .NET, particularly in modern .NET versions (.NET Core, .NET 5+), provides powerful built-in capabilities to handle JSON formatting. This guide focuses on the standard System.Text.Json library.

Using System.Text.Json for Formatting

The System.Text.Json namespace provides high-performance, low-allocating JSON APIs. It's the recommended built-in solution for .NET. Formatting options are controlled using the JsonSerializerOptions class.

Pretty-Printing (Indented Formatting)

To make the JSON output human-readable, you set the WriteIndented property of JsonSerializerOptions to True.

VB.NET Example: Pretty Print

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

Public Class Product
    Public Property Name As String
    Public Property Price As Decimal
    Public Property Tags As List(Of String)
End Class

Public Module JsonFormatter

    Public Sub FormatExample()
        Dim product As New Product With {
            .Name = "Laptop",
            .Price = 999.99D,
            .Tags = New List(Of String)({"electronics", "computer", "portable"})
        }

        ' Configure options for indented output
        Dim options As New JsonSerializerOptions With {
            .WriteIndented = True
        }

        ' Serialize the object to JSON with indentation
        Dim jsonString = JsonSerializer.Serialize(product, options)

        Console.WriteLine("Pretty-Printed JSON:")
        Console.WriteLine(jsonString)

        ' Expected Output (structure):
        '{
        '  "Name": "Laptop",
        '  "Price": 999.99,
        '  "Tags": [
        '    "electronics",
        '    "computer",
        '    "portable"
        '  ]
        '}'

    End Sub

End Module

This will produce JSON output with line breaks and indentation, making the hierarchy of the data structure visually clear.

Compact Formatting (Minified)

For a compact output, simply omit the JsonSerializerOptions or set WriteIndented to False (which is the default behavior).

VB.NET Example: Compact Format

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

Public Class Product
    Public Property Name As String
    Public Property Price As Decimal
    Public Property Tags As List(Of String)
End Class

Public Module JsonFormatter

    Public Sub CompactExample()
        Dim product As New Product With {
            .Name = "Laptop",
            .Price = 999.99D,
            .Tags = New List(Of String)({"electronics", "computer", "portable"})
        }

        ' Default options (compact)
        Dim options As New JsonSerializerOptions With {
             .WriteIndented = False ' Or just use New JsonSerializerOptions()
        }

        ' Serialize the object to JSON without indentation
        Dim jsonString = JsonSerializer.Serialize(product, options)
        ' Or simply: Dim jsonString = JsonSerializer.Serialize(product) ' Uses default compact options

        Console.WriteLine("Compact JSON:")
        Console.WriteLine(jsonString)

        ' Expected Output:
        '{"Name":"Laptop","Price":999.99,"Tags":["electronics","computer","portable"]}'

    End Sub

End Module

This format removes all non-essential whitespace, resulting in the smallest possible JSON string for the data.

Other JsonSerializerOptions

Beyond indentation, JsonSerializerOptions offers several other properties that can influence the output format and behavior:

  • PropertyNamingPolicy: Controls how property names are written (e.g., camelCase, PascalCase).
    New JsonSerializerOptions With { .PropertyNamingPolicy = JsonNamingPolicy.CamelCase }
  • DictionaryKeyPolicy: Controls how dictionary keys are written.
  • DefaultIgnoreCondition: Specifies when properties should be ignored during serialization (e.g., ignore null values).
    New JsonSerializerOptions With { .DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }
  • Converters: Allows for custom handling of specific types (e.g., formatting dates).
  • Encoder: Allows control over character escaping.

VB.NET Example: Camel Case + Ignore Null

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

Public Class UserProfile
    Public Property UserId As Integer
    Public Property UserName As String
    Public Property Email As String? ' Nullable String
    Public Property IsActive As Boolean
End Class

Public Module JsonFormatter

    Public Sub AdvancedOptionsExample()
        Dim user1 As New UserProfile With {
            .UserId = 101,
            .UserName = "Alice",
            .Email = "alice@example.com",
            .IsActive = True
        }

         Dim user2 As New UserProfile With {
            .UserId = 102,
            .UserName = "Bob",
            .Email = Nothing, ' Email is null
            .IsActive = False
        }

        ' Configure options for camelCase, ignore null, and pretty print
        Dim options As New JsonSerializerOptions With {
            .PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
            .DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
            .WriteIndented = True
        }

        Dim jsonString1 = JsonSerializer.Serialize(user1, options)
        Dim jsonString2 = JsonSerializer.Serialize(user2, options)

        Console.WriteLine("User 1 JSON (CamelCase, No Nulls, Indented):")
        Console.WriteLine(jsonString1)
        ' Expected:
        '{
        '  "userId": 101,
        '  "userName": "Alice",
        '  "email": "alice@example.com",
        '  "isActive": true
        '}'

        Console.WriteLine(Environment.NewLine & "User 2 JSON (CamelCase, No Nulls, Indented):")
        Console.WriteLine(jsonString2)
        ' Expected:
        '{
        '  "userId": 102,
        '  "userName": "Bob",
        '  "isActive": false
        '}'

    End Sub

End Module

Performance Considerations

While formatting adds a tiny overhead compared to plain serialization, System.Text.Json is optimized for performance.

  • Pretty-printing involves writing extra characters (whitespace, newlines), which slightly increases processing time and output size. Use it primarily where human readability is required.
  • Compact formatting minimizes output size and is generally preferred for network transport or storage to reduce bandwidth and disk usage.

For most applications, the performance difference between indented and compact formatting with System.Text.Json will be negligible unless you are dealing with extremely large JSON documents or high-throughput scenarios where every millisecond counts.

Tooling and Workflow

While you can format JSON programmatically in VB.NET, developers often use external tools or IDE extensions for interactive formatting during development or when inspecting JSON data. However, understanding the programmatic approach is essential for applications that generate or process JSON dynamically.

  • IDEs: Visual Studio often has built-in or extension-based JSON formatters that you can use directly on JSON files or strings within the editor.
  • Online Formatters: Many websites offer free JSON formatting services. Use these with caution for sensitive data.
  • Command-Line Tools: Tools like jq (though not VB.NET specific) are powerful for processing and formatting JSON from the command line.

Remember that the VB.NET formatting capabilities discussed here are about *generating* JSON in a specific format from your .NET objects, or less commonly, re-serializing existing JSON strings using desired options.

Conclusion

Formatting JSON in Visual Basic .NET is straightforward using the built-in System.Text.Json library and the JsonSerializerOptions class. Whether you need human-readable, indented output for debugging or compact, minified JSON for performance and size efficiency, the framework provides the necessary tools. Understanding how to configure these options is a valuable skill for any VB.NET developer working with JSON data.

Need help with your JSON?

Try our JSON Formatter tool to automatically identify and fix syntax errors in your JSON. JSON Formatter tool