Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 36 ยท Files and Databases

JSON and XML Serialization

Learn VB.NET JSON and XML handling - System.Text.Json serialize and deserialize, JsonSerializerOptions, XML literals, XElement and LINQ to XML, XmlSerializer - with read-only VB and runnable C# stand-ins.

Objects live in memory; files and networks carry text. Serialization converts an object graph to text (or bytes) and deserialization rebuilds it. The two formats you will meet most are JSON (web APIs, settings) and XML (older systems, configuration, documents). VB.NET is unusually good at XML thanks to language-level XML literals.

VB code here is read-only because the VB compiler is not available on this site. The runnable blocks are C# stand-ins that use the same classes (System.Text.Json, System.Xml.Linq, XmlSerializer) in the shared .NET library.

JSON with System.Text.Json

VB
Imports System.Text.Json

Public Class Book
    Public Property Title As String
    Public Property Pages As Integer
    Public Property Tags As List(Of String)
End Class

Dim b As New Book With {.Title = "VB Basics", .Pages = 320, .Tags = New List(Of String) From {"vb", "intro"}}

Dim json As String = JsonSerializer.Serialize(b)
Dim back As Book = JsonSerializer.Deserialize(Of Book)(json)

Serialization turns public properties into JSON members; deserialization needs a public parameterless constructor (or a supported constructor) and settable properties. Fields are ignored by default.

Options customize the output through JsonSerializerOptions:

Option Effect
WriteIndented = True Pretty-printed output
PropertyNamingPolicy = JsonNamingPolicy.CamelCase title instead of Title
PropertyNameCaseInsensitive = True Accept any casing when reading
DefaultIgnoreCondition = WhenWritingNull Skip null values
Converters.Add(New JsonStringEnumConverter()) Enums as names, not numbers

Attributes such as <JsonPropertyName("page_count")> and <JsonIgnore> work per property.

C# Serialize and deserialize with options

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Reading JSON without a class

When the shape is unknown or you need one value, parse into a document and walk it:

VB
Using doc = JsonDocument.Parse(json)
    Dim title = doc.RootElement.GetProperty("title").GetString()
    For Each tag In doc.RootElement.GetProperty("tags").EnumerateArray()
        Console.WriteLine(tag.GetString())
    Next
End Using
C# JsonDocument for ad-hoc reads

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

XML: literals and LINQ to XML

VB can embed XML directly in code, with <%= ... %> holes for values and XML axis properties for reading:

VB
Dim name = "Ada"
Dim person = <person id="1">
                 <name><%= name %></name>
                 <langs>
                     <lang>VB</lang>
                     <lang>C#</lang>
                 </langs>
             </person>

Console.WriteLine(person.<name>.Value)             ' child element
Console.WriteLine(person.@id)                      ' attribute
For Each l In person...<lang>                      ' descendants
    Console.WriteLine(l.Value)
Next

Under the surface this is LINQ to XML: XElement, XAttribute, XDocument. C# has no literals but the same object model.

C# LINQ to XML (the engine behind VB XML literals)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

XmlSerializer

XmlSerializer converts classes to XML much like JsonSerializer does for JSON; attributes such as <XmlAttribute>, <XmlElement> and <XmlIgnore> shape the result. It requires a public parameterless constructor and public properties.

C# XmlSerializer round trip

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Choosing a format

JSON XML
Size Compact Verbose
Attributes/namespaces/schemas No Yes
Comments No Yes
Typical use Web APIs, settings Config, documents, legacy systems

For new designs pick JSON unless you must interoperate with XML. See also text files for saving the result to disk.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which JSON option makes property names start with a lowercase letter?

    JsonNamingPolicy.CamelCase converts Title to title.
  2. 2. What does System.Text.Json ignore by default when serializing?

    Fields are skipped unless IncludeFields is enabled.
  3. 3. What are VB XML literals compiled to?

    They create XElement/XAttribute trees from System.Xml.Linq.
  4. 4. Which class do you use to read JSON of unknown shape?

    JsonDocument.Parse lets you navigate elements without defining classes.

Summary

  • JsonSerializer.Serialize/Deserialize map public properties; configure with JsonSerializerOptions and attributes.
  • JsonDocument reads unknown JSON.
  • VB XML literals and XElement build and query XML; <%= %> embeds values.
  • XmlSerializer maps classes to XML with attribute hints.

Next: ADO.NET and DataTables