SlideShare a Scribd company logo
Working with XML and JSON Serializing
2
 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
7/21/2022
Objectives
Overview .NET Serialization
7/21/2022 4
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)
7/21/2022 5
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
 JsonSerializer: Provides functionality to serialize objects or value types to
JSON and to deserialize JSON into objects or value types
 The Data Contract Serializer: Serializes and deserializes an instance of a type
into an XML stream or document using a supplied Data Contract (classes)
7/21/2022 6
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
a data stream. When the object is subsequently deserialized, an exact clone of
the original object is created
7/21/2022 7
How Serialization Works
 The object is serialized to a stream that carries the data. The stream may also
have information about the object's type, such as its version, culture, and
assembly name. From that stream, the object can be stored in a database, a
file, or memory
7/21/2022 8
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
 Passing an object from one domain to another
 Passing an object through a firewall as a JSON or XML string
 Maintaining security or user-specific information across applications
Overview XML Serialization
7/21/2022 10
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
7/21/2022 11
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
XmlDataProvider in WPF Application
Demonstration
7/21/2022 13
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 &amp; The Horn</Company>
<Phone>(171) 555-7788</Phone>
</Contact>
<Contact Id="003">
<ContactName >Elizabeth Lincoln</ContactName>
<Company>Bottom-Dollar &amp; Markets</Company>
<Phone>(604) 555-4729</Phone>
</Contact>
</ContactList>
7/21/2022 14
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>
7/21/2022 15
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>
7/21/2022 16
5.Press Crtl+F5 to run project
7/21/2022 17
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
7/21/2022 18
Understanding XmlSerializer
Method Name Description
CreateReader() Returns an object used to read the XML document to be serialized
CreateWriter() When overridden in a derived class, returns a writer used to serialize the object
Deserialize(Stream) Deserializes the XML document contained by the specified Stream
Deserialize(TextReader) Deserializes the XML document contained by the specified TextReader
Serialize(Stream, Object)
Serializes the specified Object and writes the XML document to a file using the
specified Stream
Serialize(TextWriter, Object)
Serializes the specified Object and writes the XML document to a file using the
specified TextWriter
 The following table describes some of the methods of the XmlSerializer class:
Serializing as XML Demonstration
7/21/2022 20
1. Create a Console app named DemoXmlSerializer
2. Write code for Program.cs as follows then press Ctrl+F5 to run project
XmlSerializer Demo-01
7/21/2022 21
1. Create a Console app named DemoXmlSerializer02
2. Right-click on the project , select Add | Class named Person.cs then write codes as
follows:
3. Write code for Program.cs as follows then press Ctrl+F5 to run project
XmlSerializer Demo-02
7/21/2022 22
7/21/2022 23
Overview JSON Serialization
7/21/2022 25
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
{
"firstName":"John", "lastName":"Doe"
}
 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:
7/21/2022 26
JSON Syntax Rules
 Data is in name/value pairs
 Data is separated by commas
 Curly braces hold objects
 Square brackets hold arrays
{
"employees":
[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
}
7/21/2022 27
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" }
here  / is used for Escape Character / (forward slash)
7/21/2022 28
JSON Data Types
 Number: Represented in base 10. The octal and hexadecimal formats are
not used
Example: { "age": 20 } , { "percentage": 82.44}
 Boolean: This data type can be either true or false
Example: { "result" : true }
 Null: It is just a define null value
Example: { "middlename":null }
7/21/2022 29
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}
}
7/21/2022 30
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}
]
}
7/21/2022 31
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
7/21/2022 32
Understanding JSON Serialization
Method Name Description
Deserialize(String, Type,
JsonSerializerOptions)
Parses the text representing a single JSON value into an instance
of a specified type
Deserialize(Utf8JsonReader, Type,
JsonSerializerOptions)
Reads one JSON value (including objects or arrays) from the
provided reader and converts it into an instance of a specified type
Deserialize<TValue>(String,
JsonSerializerOptions)
Parses the text representing a single JSON value into an instance
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,
JsonSerializerOptions)
Writes the JSON representation of the specified type to the
provided writer
SerializeToUtf8Bytes(Object, Type,
JsonSerializerOptions)
Converts a value of the specified type into a JSON string, encoded
as UTF-8 bytes
Serialize<TValue>(TValue,
JsonSerializerOptions)
Converts the value of a type specified by a generic type parameter
into a JSON string
 The following table describes some of the methods of the JsonSerializer class:
7/21/2022 33
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
JsonPropertyNameAttribute
Specifies the property name that is present in the JSON when serializing and
deserializing. This overrides any naming policy specified by JsonNamingPolicy
JsonExtensionDataAttribute
When placed on a property of type IDictionary<TKey,TValue>, any properties that
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
JsonNumberHandlingAttribute
When placed on a type, property, or field, indicates what JsonNumberHandling
settings should be used when serializing or deserializing numbers
7/21/2022 34
Controlling Serialization with Attributes Demo
//…
using System.Text.Json;
using System.Text.Json.Serialization;
7/21/2022 35
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
WriteIndented
Gets or sets a value that defines whether JSON should use pretty printing. By
default, JSON is serialized without any extra white space
AllowTrailingCommas
Get or sets a value that indicates whether an extra comma at the end of a list of
JSON values in an object or array is allowed (and ignored) within the JSON
payload being deserialized
ReadCommentHandling
Gets or sets a value that defines how comments are handled during
deserialization
PropertyNameCaseInsensitive
Gets or sets a value that determines whether a property's name uses a case-
insensitive comparison during deserialization. The default value is false
ReferenceHandler Configures how object references are handled when reading and writing JSON
7/21/2022 36
JSON Serialization Options
Property Name Description
PropertyNamingPolicy
Gets or sets a value that specifies the policy used to convert a property's name on
an object to another format, such as camel-casing, or null to leave property names
unchanged
DictionaryKeyPolicy
Gets or sets the policy used to convert a IDictionary key's name to another format,
such as camel-casing
Encoder
Gets or sets the encoder to use when escaping strings, or null to use the default
encoder
IgnoreNullValues
ets or sets a value that determines whether null values are ignored during
serialization and deserialization. The default value is false.
IgnoreReadOnlyProperties
Determines whether read-only fields are ignored during serialization. A field is
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
7/21/2022 37
JSON Serialization Options Demo
//…
using System.Text.Json;
using System.Text.Json.Serialization;
7/21/2022 38
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)
7/21/2022 39
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
Serializing as Json Demonstration
7/21/2022 41
1.Create a WPF app named ManageProductsApp includes a window named
WindowManageProducts.xaml that has controls as follows :
ListView
Control
TextBox
Control
Label Control
Button Control
7/21/2022 42
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>
</DockPanel>
</Window>
View details in
next slide
7/21/2022 43
XAML code of Grid tag
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel Background="LightBlue" Orientation ="Vertical"
HorizontalAlignment="Left" Width="400">
<Label Name="lblInstruction" Foreground="Red" FontWeight="DemiBold"
FontSize="20" Content="Product Information"/>
<Label Name="lblProductID" Content="ProductID"/>
<TextBox Name="txtProductID" HorizontalAlignment="Left"
Height="25" Width="300"
Text="{Binding Path=ProductID, Mode=OneWay}"
DataContext="{Binding ElementName=lvProducts, Path=SelectedItem}" />
<Label Name="lbProductName" Content="Product Name" />
<TextBox Name="txtProductName" HorizontalAlignment="Left"
Height="25" Width="300" Text="{Binding Path=ProductName, Mode=OneWay}"
DataContext="{Binding ElementName=lvProducts, Path=SelectedItem}" />
7/21/2022 44
XAML code of Grid tag (cont.)
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
<Button x:Name="btnInsert" Margin="10" Width="70" Content="Insert"
Click="btnInsert_Click" />
<Button x:Name="btnUpdate" Margin="10" Width="70" Content="Update"
Click="btnUpdate_Click"/>
<Button x:Name="btnDelete" Margin="10" Width="70" Content="Delete"
Click="btnDelete_Click"/>
</StackPanel>
</StackPanel>
<ListView Grid.Row="1" Name="lvProducts" Width="400" >
<ListView.View>
<GridView>
<GridViewColumn Header="Product ID" Width="100"
DisplayMemberBinding="{Binding Path=ProductID }"/>
<GridViewColumn Header="Product Name" Width="200"
DisplayMemberBinding="{Binding Path=ProductName}"/>
</GridView>
</ListView.View>
</ListView>
</Grid>
7/21/2022 45
2.Right-click on the project | Add | Class, named ManageProducts.cs then write codes
as follows:
7/21/2022 46
7/21/2022 47
3.Write codes in WindowManageProducts.xaml.cs as follows
7/21/2022 48
7/21/2022 49
7/21/2022 50
4. Press Ctrl+F5 to run project and view the output
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

More Related Content

PPTX
Xml serialization
PPT
It seminar-xml serialization
PPT
It seminar-xml serialization
PDF
Tool Development 05 - XML Schema, INI, JSON, YAML
PPTX
LU 1.3. JSON & XML.pptx about how they work and introduction
PPTX
C# Binary serialization
PPT
GTR-Python-Using Web Services notesgtr.ppt
PDF
Difference between xml and json
Xml serialization
It seminar-xml serialization
It seminar-xml serialization
Tool Development 05 - XML Schema, INI, JSON, YAML
LU 1.3. JSON & XML.pptx about how they work and introduction
C# Binary serialization
GTR-Python-Using Web Services notesgtr.ppt
Difference between xml and json

Similar to Working with XML and JSON Serializing (20)

PPTX
Applied xml programming for microsoft
PDF
C# 10 in a Nutshell_ The Definitive Reference-O'Reilly Media (2022).pdf
PPTX
Net serialization
PPTX
X++ 1.pptx
PDF
Dot Net Fundamentals
PDF
The JSON architecture
PDF
Basics of JSON (JavaScript Object Notation) with examples
PDF
Intro to JSON
PDF
Moving from webservices to wcf services
PPT
Web Services Part 1
DOC
Serialization in .NET
PPTX
Optimizing Application Architecture (.NET/Java topics)
PPTX
C# Xml serialization
PPT
IntroToCSharpcode.ppt
PPTX
Data exchange over internet (XML vs JSON)
PDF
C 7 0 in a Nutshell The Definitive Reference 7th Edition Joseph Albahari
PPTX
MWLUG 2014: Modern Domino (workshop)
Applied xml programming for microsoft
C# 10 in a Nutshell_ The Definitive Reference-O'Reilly Media (2022).pdf
Net serialization
X++ 1.pptx
Dot Net Fundamentals
The JSON architecture
Basics of JSON (JavaScript Object Notation) with examples
Intro to JSON
Moving from webservices to wcf services
Web Services Part 1
Serialization in .NET
Optimizing Application Architecture (.NET/Java topics)
C# Xml serialization
IntroToCSharpcode.ppt
Data exchange over internet (XML vs JSON)
C 7 0 in a Nutshell The Definitive Reference 7th Edition Joseph Albahari
MWLUG 2014: Modern Domino (workshop)
Ad

More from ssusere19c741 (19)

PDF
0-Slot21-22-Strings.pdf
PDF
0-Slot18-19-20-ContiguousStorage.pdf
PDF
0-Slot14-15-16-Libraries.pdf
PDF
0-Slot13-Programming-With-Menu.pdf
PDF
0-Slot11-12-Pointers.pdf
PDF
0-Slot08-09-10-Module-Functions.pdf
PDF
0-Slot05-06-07-Basic-Logics.pdf
PDF
0-Slot02-Introduction-to-PFC.pdf
PDF
Intro-InstallingTool-FirstProgram
PPTX
Background Tasks with Worker Service
PPTX
Real-Time Communication
PPTX
Building Websites Using ASP.NET Core Razor Pages
PPTX
Dependency Injection in .NET
PPTX
Asynchronous and Parallel Programming in .NET
PPTX
Networking Programming
PPTX
Building Windows Presentation Foundation (WPF) Application
PPTX
Course Introduction
PPTX
Building Windows Presentation Foundation (WPF) Application
PPTX
Course Introduction
0-Slot21-22-Strings.pdf
0-Slot18-19-20-ContiguousStorage.pdf
0-Slot14-15-16-Libraries.pdf
0-Slot13-Programming-With-Menu.pdf
0-Slot11-12-Pointers.pdf
0-Slot08-09-10-Module-Functions.pdf
0-Slot05-06-07-Basic-Logics.pdf
0-Slot02-Introduction-to-PFC.pdf
Intro-InstallingTool-FirstProgram
Background Tasks with Worker Service
Real-Time Communication
Building Websites Using ASP.NET Core Razor Pages
Dependency Injection in .NET
Asynchronous and Parallel Programming in .NET
Networking Programming
Building Windows Presentation Foundation (WPF) Application
Course Introduction
Building Windows Presentation Foundation (WPF) Application
Course Introduction
Ad

Recently uploaded (20)

PPT
UNIT I- Yarn, types, explanation, process
PPT
EGWHermeneuticsffgggggggggggggggggggggggggggggggg.ppt
PPTX
BSCS lesson 3.pptxnbbjbb mnbkjbkbbkbbkjb
PPT
pump pump is a mechanism that is used to transfer a liquid from one place to ...
PDF
Key Trends in Website Development 2025 | B3AITS - Bow & 3 Arrows IT Solutions
PPTX
areprosthodontics and orthodonticsa text.pptx
PDF
UNIT 1 Introduction fnfbbfhfhfbdhdbdto Java.pptx.pdf
DOCX
actividad 20% informatica microsoft project
PPTX
CLASS_11_BUSINESS_STUDIES_PPT_CHAPTER_1_Business_Trade_Commerce.pptx
PPTX
mahatma gandhi bus terminal in india Case Study.pptx
PDF
Emailing DDDX-MBCaEiB.pdf DDD_Europe_2022_Intro_to_Context_Mapping_pdf-165590...
PPTX
DOC-20250430-WA0014._20250714_235747_0000.pptx
PPTX
Fundamental Principles of Visual Graphic Design.pptx
PPTX
ANATOMY OF ANTERIOR CHAMBER ANGLE AND GONIOSCOPY.pptx
PPTX
HPE Aruba-master-icon-library_052722.pptx
DOCX
The story of the first moon landing.docx
PDF
BRANDBOOK-Presidential Award Scheme-Kenya-2023
PPTX
6- Architecture design complete (1).pptx
PPT
Machine printing techniques and plangi dyeing
PDF
Quality Control Management for RMG, Level- 4, Certificate
UNIT I- Yarn, types, explanation, process
EGWHermeneuticsffgggggggggggggggggggggggggggggggg.ppt
BSCS lesson 3.pptxnbbjbb mnbkjbkbbkbbkjb
pump pump is a mechanism that is used to transfer a liquid from one place to ...
Key Trends in Website Development 2025 | B3AITS - Bow & 3 Arrows IT Solutions
areprosthodontics and orthodonticsa text.pptx
UNIT 1 Introduction fnfbbfhfhfbdhdbdto Java.pptx.pdf
actividad 20% informatica microsoft project
CLASS_11_BUSINESS_STUDIES_PPT_CHAPTER_1_Business_Trade_Commerce.pptx
mahatma gandhi bus terminal in india Case Study.pptx
Emailing DDDX-MBCaEiB.pdf DDD_Europe_2022_Intro_to_Context_Mapping_pdf-165590...
DOC-20250430-WA0014._20250714_235747_0000.pptx
Fundamental Principles of Visual Graphic Design.pptx
ANATOMY OF ANTERIOR CHAMBER ANGLE AND GONIOSCOPY.pptx
HPE Aruba-master-icon-library_052722.pptx
The story of the first moon landing.docx
BRANDBOOK-Presidential Award Scheme-Kenya-2023
6- Architecture design complete (1).pptx
Machine printing techniques and plangi dyeing
Quality Control Management for RMG, Level- 4, Certificate

Working with XML and JSON Serializing

  • 1. Working with XML and JSON Serializing
  • 2. 2  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 7/21/2022 Objectives
  • 4. 7/21/2022 4 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)
  • 5. 7/21/2022 5 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  JsonSerializer: Provides functionality to serialize objects or value types to JSON and to deserialize JSON into objects or value types  The Data Contract Serializer: Serializes and deserializes an instance of a type into an XML stream or document using a supplied Data Contract (classes)
  • 6. 7/21/2022 6 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 a data stream. When the object is subsequently deserialized, an exact clone of the original object is created
  • 7. 7/21/2022 7 How Serialization Works  The object is serialized to a stream that carries the data. The stream may also have information about the object's type, such as its version, culture, and assembly name. From that stream, the object can be stored in a database, a file, or memory
  • 8. 7/21/2022 8 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  Passing an object from one domain to another  Passing an object through a firewall as a JSON or XML string  Maintaining security or user-specific information across applications
  • 10. 7/21/2022 10 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
  • 11. 7/21/2022 11 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
  • 12. XmlDataProvider in WPF Application Demonstration
  • 13. 7/21/2022 13 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 &amp; The Horn</Company> <Phone>(171) 555-7788</Phone> </Contact> <Contact Id="003"> <ContactName >Elizabeth Lincoln</ContactName> <Company>Bottom-Dollar &amp; Markets</Company> <Phone>(604) 555-4729</Phone> </Contact> </ContactList>
  • 14. 7/21/2022 14 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>
  • 15. 7/21/2022 15 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>
  • 17. 7/21/2022 17 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
  • 18. 7/21/2022 18 Understanding XmlSerializer Method Name Description CreateReader() Returns an object used to read the XML document to be serialized CreateWriter() When overridden in a derived class, returns a writer used to serialize the object Deserialize(Stream) Deserializes the XML document contained by the specified Stream Deserialize(TextReader) Deserializes the XML document contained by the specified TextReader Serialize(Stream, Object) Serializes the specified Object and writes the XML document to a file using the specified Stream Serialize(TextWriter, Object) Serializes the specified Object and writes the XML document to a file using the specified TextWriter  The following table describes some of the methods of the XmlSerializer class:
  • 19. Serializing as XML Demonstration
  • 20. 7/21/2022 20 1. Create a Console app named DemoXmlSerializer 2. Write code for Program.cs as follows then press Ctrl+F5 to run project XmlSerializer Demo-01
  • 21. 7/21/2022 21 1. Create a Console app named DemoXmlSerializer02 2. Right-click on the project , select Add | Class named Person.cs then write codes as follows: 3. Write code for Program.cs as follows then press Ctrl+F5 to run project XmlSerializer Demo-02
  • 25. 7/21/2022 25 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 { "firstName":"John", "lastName":"Doe" }  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:
  • 26. 7/21/2022 26 JSON Syntax Rules  Data is in name/value pairs  Data is separated by commas  Curly braces hold objects  Square brackets hold arrays { "employees": [ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] }
  • 27. 7/21/2022 27 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" } here / is used for Escape Character / (forward slash)
  • 28. 7/21/2022 28 JSON Data Types  Number: Represented in base 10. The octal and hexadecimal formats are not used Example: { "age": 20 } , { "percentage": 82.44}  Boolean: This data type can be either true or false Example: { "result" : true }  Null: It is just a define null value Example: { "middlename":null }
  • 29. 7/21/2022 29 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} }
  • 30. 7/21/2022 30 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} ] }
  • 31. 7/21/2022 31 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
  • 32. 7/21/2022 32 Understanding JSON Serialization Method Name Description Deserialize(String, Type, JsonSerializerOptions) Parses the text representing a single JSON value into an instance of a specified type Deserialize(Utf8JsonReader, Type, JsonSerializerOptions) Reads one JSON value (including objects or arrays) from the provided reader and converts it into an instance of a specified type Deserialize<TValue>(String, JsonSerializerOptions) Parses the text representing a single JSON value into an instance 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, JsonSerializerOptions) Writes the JSON representation of the specified type to the provided writer SerializeToUtf8Bytes(Object, Type, JsonSerializerOptions) Converts a value of the specified type into a JSON string, encoded as UTF-8 bytes Serialize<TValue>(TValue, JsonSerializerOptions) Converts the value of a type specified by a generic type parameter into a JSON string  The following table describes some of the methods of the JsonSerializer class:
  • 33. 7/21/2022 33 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 JsonPropertyNameAttribute Specifies the property name that is present in the JSON when serializing and deserializing. This overrides any naming policy specified by JsonNamingPolicy JsonExtensionDataAttribute When placed on a property of type IDictionary<TKey,TValue>, any properties that 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 JsonNumberHandlingAttribute When placed on a type, property, or field, indicates what JsonNumberHandling settings should be used when serializing or deserializing numbers
  • 34. 7/21/2022 34 Controlling Serialization with Attributes Demo //… using System.Text.Json; using System.Text.Json.Serialization;
  • 35. 7/21/2022 35 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 WriteIndented Gets or sets a value that defines whether JSON should use pretty printing. By default, JSON is serialized without any extra white space AllowTrailingCommas Get or sets a value that indicates whether an extra comma at the end of a list of JSON values in an object or array is allowed (and ignored) within the JSON payload being deserialized ReadCommentHandling Gets or sets a value that defines how comments are handled during deserialization PropertyNameCaseInsensitive Gets or sets a value that determines whether a property's name uses a case- insensitive comparison during deserialization. The default value is false ReferenceHandler Configures how object references are handled when reading and writing JSON
  • 36. 7/21/2022 36 JSON Serialization Options Property Name Description PropertyNamingPolicy Gets or sets a value that specifies the policy used to convert a property's name on an object to another format, such as camel-casing, or null to leave property names unchanged DictionaryKeyPolicy Gets or sets the policy used to convert a IDictionary key's name to another format, such as camel-casing Encoder Gets or sets the encoder to use when escaping strings, or null to use the default encoder IgnoreNullValues ets or sets a value that determines whether null values are ignored during serialization and deserialization. The default value is false. IgnoreReadOnlyProperties Determines whether read-only fields are ignored during serialization. A field is 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
  • 37. 7/21/2022 37 JSON Serialization Options Demo //… using System.Text.Json; using System.Text.Json.Serialization;
  • 38. 7/21/2022 38 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)
  • 39. 7/21/2022 39 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
  • 40. Serializing as Json Demonstration
  • 41. 7/21/2022 41 1.Create a WPF app named ManageProductsApp includes a window named WindowManageProducts.xaml that has controls as follows : ListView Control TextBox Control Label Control Button Control
  • 42. 7/21/2022 42 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> </DockPanel> </Window> View details in next slide
  • 43. 7/21/2022 43 XAML code of Grid tag <Grid> <Grid.RowDefinitions> <RowDefinition Height="*"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <StackPanel Background="LightBlue" Orientation ="Vertical" HorizontalAlignment="Left" Width="400"> <Label Name="lblInstruction" Foreground="Red" FontWeight="DemiBold" FontSize="20" Content="Product Information"/> <Label Name="lblProductID" Content="ProductID"/> <TextBox Name="txtProductID" HorizontalAlignment="Left" Height="25" Width="300" Text="{Binding Path=ProductID, Mode=OneWay}" DataContext="{Binding ElementName=lvProducts, Path=SelectedItem}" /> <Label Name="lbProductName" Content="Product Name" /> <TextBox Name="txtProductName" HorizontalAlignment="Left" Height="25" Width="300" Text="{Binding Path=ProductName, Mode=OneWay}" DataContext="{Binding ElementName=lvProducts, Path=SelectedItem}" />
  • 44. 7/21/2022 44 XAML code of Grid tag (cont.) <StackPanel Orientation="Horizontal" HorizontalAlignment="Left"> <Button x:Name="btnInsert" Margin="10" Width="70" Content="Insert" Click="btnInsert_Click" /> <Button x:Name="btnUpdate" Margin="10" Width="70" Content="Update" Click="btnUpdate_Click"/> <Button x:Name="btnDelete" Margin="10" Width="70" Content="Delete" Click="btnDelete_Click"/> </StackPanel> </StackPanel> <ListView Grid.Row="1" Name="lvProducts" Width="400" > <ListView.View> <GridView> <GridViewColumn Header="Product ID" Width="100" DisplayMemberBinding="{Binding Path=ProductID }"/> <GridViewColumn Header="Product Name" Width="200" DisplayMemberBinding="{Binding Path=ProductName}"/> </GridView> </ListView.View> </ListView> </Grid>
  • 45. 7/21/2022 45 2.Right-click on the project | Add | Class, named ManageProducts.cs then write codes as follows:
  • 47. 7/21/2022 47 3.Write codes in WindowManageProducts.xaml.cs as follows
  • 50. 7/21/2022 50 4. Press Ctrl+F5 to run project and view the output
  • 51. 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