Chapter 10 - Working With XML and JSON Serializing
Chapter 10 - Working With XML and JSON Serializing
Objectives
Overview Serialization in .NET
Understanding Serialization Engines in .NET
Explain about how serialization works
Describe use Serialization
Overview XML Serialization
Overview JSON (JavaScript Object Notation) Serialization
Create demo using XML with WPF application
Create demo XML Serialization in .NET application
Create demo JSON Serialization in .NET application
08/03/2024 2
Overview .NET Serialization
Understanding Serialization in .NET
Serialization is the act of taking an in-memory object or object graph (set of
objects that reference one another) and flattening it into a stream of bytes, XML,
JSON, or a similar representation that can be stored or transmitted
Deserialization works in reverse, taking a data stream and reconstituting it into
an in-memory object or object graph
There are four serialization engines in .NET :
XmlSerializer (XML)
JsonSerializer (JSON)
The data contract serializer (XML and JSON)
The binary serializer (binary)
08/03/2024 4
Understanding Serialization Engines
XmlSerializer: Serializes and deserializes objects into and from XML
documents. The XmlSerializer enables us to control how objects are encoded
into XML
08/03/2024 5
Understanding Serialization Engines
The Binary Serializer: Serialization can be defined as the process of storing
the state of an object to a storage medium. During this process, the public and
private fields of the object and the name of the class, including the assembly
containing the class, are converted to a stream of bytes, which is then written to
08/03/2024 7
Uses for Serialization
Serialization allows the developer to save the state of an object and re-create it
as needed, providing storage of objects as well as data exchange. Through
serialization, a developer can perform actions such as:
Sending the object to a remote application by using a web service
08/03/2024 8
Overview XML Serialization
What is the XML?
XML stands for Extensible Markup Language. It is a text-based markup
language derived from Standard Generalized Markup Language (SGML)
XML tags identify the data and are used to store and organize the data, rather
than specifying how to display it like HTML tags, which are used to display the
data. There are three important characteristics of XML that make it useful in a
variety of systems and solutions:
XML is extensible: XML allows us to create our self-descriptive tags, or language, that
suits our the application
XML carries the data, does not present it: XML allows us to store the data irrespective of
how it will be presented
XML is a public standard: XML was developed by an organization called the World Wide
Web Consortium (W3C) and is available as an open standard
08/03/2024 10
What is the XML?
An XML document can have only one root element. The following diagram
depicts the syntax rules to write different types of markup and text in an XML
document
08/03/2024 11
XmlDataProvider in WPF Application
Demonstration
1.Create a WPF app named ContactListApp
2.Right-click on the project | Add | New Item, select XML File then rename to
Contacts.xml , click Add and write contents as follows:
<?xml version="1.0" encoding="utf-8" ?>
<ContactList>
<Contact Id="001">
<ContactName >Maria Anders</ContactName>
<Company>Alfreds Futterkiste</Company>
<Phone>030-0074321</Phone>
</Contact>
<Contact Id="002">
<ContactName >Thomas Hardy</ContactName>
<Company>Around & The Horn</Company>
<Phone>(171) 555-7788</Phone>
</Contact>
<Contact Id="003">
<ContactName >Elizabeth Lincoln</ContactName>
<Company>Bottom-Dollar & Markets</Company>
<Phone>(604) 555-4729</Phone>
</Contact>
</ContactList>
08/03/2024 13
3.Right-click on the project, select Edit Project File and write config information as follows
then press Crtl+S to save:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net5.0-windows</TargetFramework>
<UseWPF>true</UseWPF>
</PropertyGroup>
<ItemGroup>
<Content Include="Contacts.xml">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project>
08/03/2024 14
4.Write code for MainWindow.xaml as follows:
<Window x:Class="ContactListApp.MainWindow"
//xmlns:……
Title="Contact List" Height="300" SizeToContent="Width" WindowStartupLocation="CenterScreen">
<Window.Resources>
<XmlDataProvider Source="Contacts.xml" XPath="ContactList/Contact" x:Key="ContactList"/>
</Window.Resources>
<Grid>
<ListView Name="lvContacts" Margin="31,14,31,16"
ItemsSource="{Binding Source={StaticResource ContactList}}">
<ListView.View>
<GridView>
<GridViewColumn Header="Id" DisplayMemberBinding="{Binding XPath=@Id}"/>
<GridViewColumn Header="Contact Name" Width="100"
DisplayMemberBinding="{Binding XPath=ContactName }"/>
<GridViewColumn Header="Company" Width="200"
DisplayMemberBinding="{Binding XPath=Company}"/>
<GridViewColumn Header="Phone" Width="150"
DisplayMemberBinding="{Binding XPath=Phone}"/>
</GridView>
</ListView.View>
</ListView>
</Grid>
</Window>
08/03/2024 15
5.Press Crtl+F5 to run project
08/03/2024 16
Understanding XmlSerializer
The XML serialization engine can produce only XML, and it is less powerful than
the binary and data contract serializers in saving and restoring a complex object
The XML serialization is the process of converting an object's public properties
and fields to a serial format (in this case, XML) for storage or transport.
Deserialization re-creates the object in its original state from the XML output
The data in our objects is described using programming language constructs
like classes, fields, properties, primitive types, arrays, and even embedded
XML in the form of XmlElement or XmlAttribute objects
08/03/2024 17
Understanding XmlSerializer
The following table describes some of the methods of the XmlSerializer class:
Method Name Description
Serializes the specified Object and writes the XML document to a file using the
Serialize(Stream, Object)
specified Stream
Serializes the specified Object and writes the XML document to a file using the
Serialize(TextWriter, Object)
specified TextWriter
08/03/2024 18
Serializing as XML Demonstration
XmlSerializer Demo-01
1. Create a Console app named DemoXmlSerializer
2. Write code for Program.cs as follows then press Ctrl+F5 to run project
08/03/2024 20
XmlSerializer Demo-02
3. Write code for Program.cs as follows then press Ctrl+F5 to run project
08/03/2024 21
08/03/2024 22
08/03/2024 23
Overview JSON Serialization
What is the JSON?
JSON stands for JavaScript Object Notation
JSON is a lightweight format for storing and transporting data
JSON is often used when data is sent from a server to a web page
JSON is "self-describing" and easy to understand
JSON data is written as name/value pairs, just like JavaScript object
properties. A name/value pair consists of a field name (in double quotes),
followed by a colon, followed by a value:
{
"firstName":"John", "lastName":"Doe"
}
08/03/2024 25
JSON Syntax Rules
Data is in name/value pairs Curly braces hold objects
Data is separated by commas Square brackets hold arrays
{
"employees":
[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
}
08/03/2024 26
JSON Data Types
JSON supports mainly 06 data types: String, Number, Boolean, null, Object,
and Array
String: JSON strings must be written in double quotes like C-language there
are various special characters(Escape Characters) in JSON that you can use
in strings such as \ (backslash), / (forward slash), b (backspace), n (new line), r
(carriage return), t (horizontal tab), etc
Example:
{ "name":"Vivek" }
{ "city":"Delhi\/India" }
08/03/2024 28
JSON Data Types
Object: It is a set of name or value pairs inserted between {} (curly braces).
The keys must be strings and should be unique and multiple key and value
pairs are separated by a, (comma)
Syntax:
{ key : value, .......}
Example:
{
“student":{ "name":“David", "age":20, "score": 50.05}
}
08/03/2024 29
JSON Data Types
Array: It is an ordered collection of values and begins with [ (left bracket) and
ends with ] (right bracket). The values of array are separated by ,(comma)
Syntax:
[ value, .......]
Example:
{
"collection" : [
{"id" : 101},
{"id" : 102},
{"id" : 103}
]
}
08/03/2024 30
Understanding JSON Serialization
The JSON (JavaScript Object Notation) serializer is fast and efficient, and was
introduced relatively recently to .NET (.NET Core). It also offers good version
tolerance and allows the use of custom converters for flexibility
JsonSerializer is used by ASP.NET Core 3, removing the dependency on
Json.NET, though it is straightforward to opt back in to Json.NET should its
features be required
JsonSerializer (in the System.Text.Json namespace) is straightforward to use
because of the simplicity of the JSON format. The root of a JSON document is
either an array or an object. Under that root are properties, which can be an
object, array, string, number, "true", "false", or "null"
The JSON serializer directly maps class property names to property names in
JSON
08/03/2024 31
Understanding JSON Serialization
The following table describes some of the methods of the JsonSerializer class:
Method Name Description
Deserialize(String, Type, Parses the text representing a single JSON value into an instance
JsonSerializerOptions) of a specified type
Deserialize(Utf8JsonReader, Type, Reads one JSON value (including objects or arrays) from the
JsonSerializerOptions) provided reader and converts it into an instance of a specified type
Deserialize<TValue>(String, Parses the text representing a single JSON value into an instance
JsonSerializerOptions) of the type specified by a generic type parameter.
Serialize(Object, Type, JsonSerializerOptions) Converts the value of a specified type into a JSON string
Serialize(Utf8JsonWriter, Object, Type, Writes the JSON representation of the specified type to the
JsonSerializerOptions) provided writer
SerializeToUtf8Bytes(Object, Type, Converts a value of the specified type into a JSON string, encoded
JsonSerializerOptions) as UTF-8 bytes
Serialize<TValue>(TValue, Converts the value of a type specified by a generic type parameter
JsonSerializerOptions) into a JSON string
08/03/2024 32
Controlling Serialization with Attributes
We can control the serialization process with attributes defined in the
System.Text.Json.Serialization namespace
The following subsections present the most useful attributes:
Attribute Name Description
JsonIgnoreAttribute Prevents a property from being serialized or deserialized
Specifies the property name that is present in the JSON when serializing and
JsonPropertyNameAttribute
deserializing. This overrides any naming policy specified by JsonNamingPolicy
When placed on a property of type IDictionary<TKey,TValue>, any properties that
JsonExtensionDataAttribute do not have a matching member are added to that dictionary during deserialization
and written during serialization
JsonConverterAttribute Converts an object or value to or from JSON
JsonIncludeAttribute Indicates that the member should be included for serialization and deserialization
When placed on a type, property, or field, indicates what JsonNumberHandling
JsonNumberHandlingAttribute settings should be used when serializing or deserializing numbers
08/03/2024 33
Controlling Serialization with Attributes Demo
//…
using System.Text.Json;
using System.Text.Json.Serialization;
08/03/2024 34
JSON Serialization Options
The serializer accepts an optional JsonSerializationOptions parameter,
allowing additional control over the serialization and deserialization process
The following subsections present the most useful options:
Property Name Description
Gets or sets a value that defines whether JSON should use pretty printing. By
WriteIndented
default, JSON is serialized without any extra white space
Get or sets a value that indicates whether an extra comma at the end of a list of
AllowTrailingCommas JSON values in an object or array is allowed (and ignored) within the JSON
payload being deserialized
Gets or sets a value that defines how comments are handled during
ReadCommentHandling
deserialization
Gets or sets a value that determines whether a property's name uses a case-
PropertyNameCaseInsensitive
insensitive comparison during deserialization. The default value is false
ReferenceHandler Configures how object references are handled when reading and writing JSON
08/03/2024 35
JSON Serialization Options
Property Name Description
Gets or sets a value that specifies the policy used to convert a property's name on
PropertyNamingPolicy an object to another format, such as camel-casing, or null to leave property names
unchanged
Gets or sets the policy used to convert a IDictionary key's name to another format,
DictionaryKeyPolicy
such as camel-casing
Gets or sets the encoder to use when escaping strings, or null to use the default
Encoder
encoder
ets or sets a value that determines whether null values are ignored during
IgnoreNullValues
serialization and deserialization. The default value is false.
Determines whether read-only fields are ignored during serialization. A field is
IgnoreReadOnlyProperties
read-only if it is marked with the readonly keyword. The default value is false
MaxDepth Gets or sets the maximum depth allowed when serializing or deserializing JSON,
with the default value of 0 indicating a maximum depth of 64
08/03/2024 36
JSON Serialization Options Demo
//…
using System.Text.Json;
using System.Text.Json.Serialization;
08/03/2024 37
Json Serialization Behavior
By default, all public properties are serialized. To ignore individual properties,
use the [JsonIgnore] attribute
The default encoder escapes non-ASCII characters, HTML-sensitive characters
within the ASCII-range, and characters that must be escaped according to the
RFC 8259 JSON spec
By default, JSON is minified. To pretty-print the JSON output, set
JsonSerializerOptions.WriteIndented to true
By default, casing of JSON names matches the .NET names. To set the name
of individual properties, we can use the [JsonPropertyName] attribute
By default, fields are ignored (use [JsonInclude] attribute to include fields)
08/03/2024 38
Json Deserialization Behavior
By default, property name matching is case-sensitive
If the JSON contains a value for a read-only property, the value is ignored and
no exception is thrown. Non-public constructors are ignored by the serializer
Deserialization to immutable objects or read-only properties is supported
By default, enums are supported as numbers. We can serialize enum names
as strings
By default, fields are ignored. Use the [JsonInclude] attribute to include fields
The default maximum depth is 64
By default, comments or trailing commas in the JSON throw exceptions. To
allow comments in the JSON, we can set the JsonSerializerOptions
.ReadCommentHandling property to JsonCommentHandling.Skip
08/03/2024 39
Serializing as Json Demonstration
1.Create a WPF app named ManageProductsApp includes a window named
WindowManageProducts.xaml that has controls as follows :
TextBox
Label Control
Control
Button Control
ListView
Control
08/03/2024 41
XAML code of WindowManageProducts.xaml:
<Window x:Class="ManageProductsApp.WindowManageProducts"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Demo_JSON_Serialization"
mc:Ignorable="d"
Title="Manage Products" Height="430" Width="420"
Loaded="Window_Loaded" WindowStartupLocation="CenterScreen"
ResizeMode="NoResize">
<DockPanel VerticalAlignment="Top" Margin="10">
<Grid>
</Grid> View details in
</DockPanel> next slide
</Window>
08/03/2024 42
XAML code of Grid tag
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel Background="LightBlue" Orientation ="Vertical"
HorizontalAlignment="Left" Width="400">
08/03/2024 43
XAML code of Grid tag (cont.)
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
08/03/2024 45
08/03/2024 46
3.Write codes in WindowManageProducts.xaml.cs as follows
08/03/2024 47
08/03/2024 48
08/03/2024 49
4. Press Ctrl+F5 to run project and view the output
08/03/2024 50
Summary
Concepts were introduced:
Overview Serialization in .NET
Understanding Serialization Engines in .NET
Explain about how serialization works
Describe use Serialization
Overview XML Serialization
Overview JSON Serialization
Create demo using XML with WPF application
Create demo XML Serialization in .NET application
Create demo JSON Serialization in .NET application
51