Commit ad7c7e02 authored by delongti's avatar delongti
Browse files

* Sample code to show serialization issues that currently prevent simple...

* Sample code to show serialization issues that currently prevent simple XML->JSON->XML serialization and deserialization, plus a way to fix it (but with significant complexity for a real world example)
* Updated gitignore to include relevant .NET ignore items.
parent a7fb60d4
Pipeline #12239 passed with stage
in 17 seconds
......@@ -122,4 +122,295 @@ venv.bak/
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
\ No newline at end of file
dmypy.json
## Separating the .NET master gitignore items
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
**/Properties/launchSettings.json
# VS Code
.vscode/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Typescript v1 declaration files
typings/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush
.cr/
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
\ No newline at end of file
using PolymorphicDeSerialization.Models;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace PolymorphicDeSerialization.Converters.Json
{
public class HI1ObjectConverterFactory : JsonConverter<HI1Object>
{
public override bool CanConvert(Type typeToConvert)
{
return typeof(HI1Object).IsAssignableFrom(typeToConvert);
}
public override HI1Object? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType != JsonTokenType.StartObject)
{
throw new JsonException();
}
reader.Read();
if (reader.TokenType != JsonTokenType.PropertyName)
{
throw new JsonException();
}
string? propertyName = reader.GetString();
if (propertyName != "TypeDiscriminator")
{
throw new JsonException();
}
reader.Read();
if (reader.TokenType != JsonTokenType.Number)
{
throw new JsonException();
}
TypeDiscriminator typeDiscriminator = (TypeDiscriminator)reader.GetInt32();
HI1Object hi1Object = typeDiscriminator switch
{
TypeDiscriminator.LITaskObject => new LITaskObject(),
_ => throw new JsonException()
};
while (reader.Read())
{
if (reader.TokenType == JsonTokenType.EndObject)
{
return hi1Object;
}
if (reader.TokenType == JsonTokenType.PropertyName)
{
propertyName = reader.GetString();
reader.Read();
switch (propertyName)
{
case "Reference":
var reference = reader.GetString();
((LITaskObject)hi1Object).Reference = reference;
break;
case "TargetIdentifier":
string? targetIdentifier = reader.GetString();
((LITaskObject)hi1Object).TargetIdentifier = targetIdentifier;
break;
case "ObjectIdentifier":
var objectIdentifier = reader.GetString();
hi1Object.ObjectIdentifier = objectIdentifier;
break;
case "Generation":
var generation = reader.GetInt32();
hi1Object.Generation = generation;
break;
}
}
}
throw new JsonException();
}
public override void Write(Utf8JsonWriter writer, HI1Object value, JsonSerializerOptions options)
{
writer.WriteStartObject();
if (value is LITaskObject liTaskObject)
{
writer.WriteNumber("TypeDiscriminator", (int)TypeDiscriminator.LITaskObject);
writer.WriteString("Reference", liTaskObject.Reference);
writer.WriteString("TargetIdentifier", liTaskObject.TargetIdentifier);
}
writer.WriteString("ObjectIdentifier", value.ObjectIdentifier);
writer.WriteNumber("Generation", value.Generation);
writer.WriteEndObject();
}
}
}
\ No newline at end of file
namespace PolymorphicDeSerialization.Converters.Json
{
public enum TypeDiscriminator
{
LITaskObject
}
}
namespace PolymorphicDeSerialization.Models
{
public class HI1Message
{
public HI1Object HI1Object { get; set; }
}
}
namespace PolymorphicDeSerialization.Models
{
public class HI1Object
{
public string ObjectIdentifier { get; set; }
public int Generation { get; set; }
public void ToString()
{
Console.WriteLine(this.GetType().Name);
}
}
}
namespace PolymorphicDeSerialization.Models
{
internal class HI1ObjectWithExplicitObjectTypes
{
public LITaskObject LITaskObject { get; set; }
}
}
namespace PolymorphicDeSerialization.Models
{
public class LITaskObject : HI1Object
{
public string Reference { get; set; }
public string TargetIdentifier { get; set; }
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.2.32602.215
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PolymorphicDeSerialization", "PolymorphicDeSerialization.csproj", "{BAF94173-2087-4A72-91AA-A856B5F6C727}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{BAF94173-2087-4A72-91AA-A856B5F6C727}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BAF94173-2087-4A72-91AA-A856B5F6C727}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BAF94173-2087-4A72-91AA-A856B5F6C727}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BAF94173-2087-4A72-91AA-A856B5F6C727}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {F2379234-E654-426F-9738-A034C06EE50B}
EndGlobalSection
EndGlobal
using PolymorphicDeSerialization.Converters.Json;
using PolymorphicDeSerialization.Models;
using System.Text.Json;
// Make an LI Task Object
var lit = new LITaskObject
{
Reference = "1",
TargetIdentifier = "someperson",
ObjectIdentifier = Guid.NewGuid().ToString(),
Generation = 0
};
// Scenario 1: Normal serialization of an explicitly defined object.
PrintHeader("Serialize an object explicitly defined as LITaskObject.");
var litString = JsonSerializer.Serialize(lit);
Console.WriteLine(litString);
PrintFooter();
// Scenario 2: Normal serialization of an object assigned to a base type object.
PrintHeader("Now Serialize the same LITaskObject, but do so after assigning it to an object of type HI1Object.");
var hi1Object = lit;
var hi1ObjectString = JsonSerializer.Serialize(hi1Object);
Console.WriteLine(hi1ObjectString);
PrintFooter();
// Scenario 3: Assign the derived type to a base type property of an object. This will result in loss of data when serialized.
PrintHeader("Now make an HI1Message. This has a property of type HI1Object as it can represent any HI1Object.", false);
PrintHeader("Only the HI1Object properties will be serialized. The fields in the derived type will be lost.");
var hi1Message = new HI1Message
{
HI1Object = lit
};
var hi1MessageString = JsonSerializer.Serialize(hi1Message);
Console.WriteLine(hi1MessageString);
PrintFooter();
// Scenario 4: Create a custom serializer to handle derived types when serializing an object with properties of HI1Object and not the derived types.
PrintHeader("Now make a JsonSerializerFactory specific to HI1Object and its derived types.", false);
PrintHeader("Notice the presence of a TypeDiscriminator value. This is necessary to ensure we can deserialize later.");
var serializeOptions = new JsonSerializerOptions();
serializeOptions.Converters.Add(new HI1ObjectConverterFactory());
var serializerWithOptions = JsonSerializer.Serialize(hi1Message, serializeOptions);
Console.WriteLine(serializerWithOptions);
PrintFooter();
// Scenario 5: Assign the derived type to a version of HI1Message that has a property of type LITaskObject instead of HI1Object.
PrintHeader("Now make an HI1ObjectWithExplicitObjectTypes. This has a property of type LITaskObject.");
var hi1v2Message = new HI1ObjectWithExplicitObjectTypes
{
LITaskObject = lit
};
var hi1v2MessageString = JsonSerializer.Serialize(hi1v2Message);
Console.WriteLine(hi1v2MessageString);
PrintFooter();
void PrintHeader(string headerText, bool addNewLine = true)
{
Console.WriteLine($"{headerText}{(addNewLine ? Environment.NewLine : "")}");
}
void PrintFooter()
{
Console.WriteLine("\r\n======================================================================\r\n");
}
\ No newline at end of file
Simple app that shows how properties can be lost during serialization if the conversion
logic doesn't support polymorphism, and how you can extend that logic, but at a cost of
significantly increased maintance and risk of breaking changes.
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment