ktsu.UniversalSerializer 1.0.0

Prefix Reserved
There is a newer version of this package available.
See the version list below for details.
dotnet add package ktsu.UniversalSerializer --version 1.0.0
                    
NuGet\Install-Package ktsu.UniversalSerializer -Version 1.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="ktsu.UniversalSerializer" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="ktsu.UniversalSerializer" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="ktsu.UniversalSerializer" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add ktsu.UniversalSerializer --version 1.0.0
                    
#r "nuget: ktsu.UniversalSerializer, 1.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#addin nuget:?package=ktsu.UniversalSerializer&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=ktsu.UniversalSerializer&version=1.0.0
                    
Install as a Cake Tool

ktsu.UniversalSerializer

A unified serialization library for .NET that provides a consistent API for various serialization formats including JSON, XML, YAML, TOML, and MessagePack.

Features

  • Unified API: Serialize and deserialize objects with a consistent interface regardless of the format
  • Multiple Formats: Support for common text formats (JSON, XML, YAML, TOML) and binary formats (MessagePack)
  • Type Conversion: Built-in type conversion for non-natively supported types
  • Polymorphic Serialization: Support for inheritance and polymorphic types
  • Dependency Injection: First-class support for Microsoft DI with fluent configuration
  • Extensible: Easy to extend with custom serializers or type converters

Installation

dotnet add package ktsu.UniversalSerializer

Quick Start

// Add to your dependency injection container
services.AddUniversalSerializer();

// Use in your application
public class MyService
{
    private readonly ISerializerFactory _serializerFactory;
    
    public MyService(ISerializerFactory serializerFactory)
    {
        _serializerFactory = serializerFactory;
    }
    
    public void Process()
    {
        var data = new MyData { Id = 1, Name = "Example" };
        
        // Serialize to different formats
        var jsonSerializer = _serializerFactory.GetJsonSerializer();
        string jsonString = jsonSerializer.Serialize(data);
        
        var yamlSerializer = _serializerFactory.GetYamlSerializer();
        string yamlString = yamlSerializer.Serialize(data);
        
        var msgPackSerializer = _serializerFactory.GetMessagePackSerializer();
        byte[] binaryData = msgPackSerializer.SerializeToBytes(data);
        
        // Deserialize from string
        var deserializedJson = jsonSerializer.Deserialize<MyData>(jsonString);
        
        // Deserialize from bytes
        var deserializedBinary = msgPackSerializer.DeserializeFromBytes<MyData>(binaryData);
    }
}

public class MyData
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Advanced Configuration

Configuring Serializer Options

services.AddUniversalSerializer(builder => {
    builder.ConfigureOptions(options => {
        // Common options
        options.PrettyPrint = true;
        options.IgnoreNullValues = true;
        options.EnumFormat = EnumSerializationFormat.Name;
        
        // Format-specific options
        options.WithOption(SerializerOptionKeys.Json.AllowComments, true);
        options.WithOption(SerializerOptionKeys.Json.CaseInsensitive, true);
        options.WithOption(SerializerOptionKeys.Xml.Indent, true);
        options.WithOption(SerializerOptionKeys.MessagePack.EnableLz4Compression, true);
    });
    
    // Register only the serializers you need
    builder.AddJsonSerializer()
           .AddXmlSerializer()
           .AddYamlSerializer()
           .AddMessagePackSerializer();
});

Type Conversion

The library supports custom type conversion for types that aren't natively handled by serializers:

// Define a custom type with string conversion
public class CustomId
{
    public Guid Value { get; }
    
    public CustomId(Guid value)
    {
        Value = value;
    }
    
    // ToString for serialization
    public override string ToString()
    {
        return Value.ToString("D");
    }
    
    // Parse method for deserialization
    public static CustomId Parse(string value)
    {
        return new CustomId(Guid.Parse(value));
    }
}

// Enable string conversion in options
services.AddUniversalSerializer(builder => {
    builder.ConfigureOptions(options => {
        options.UseStringConversionForUnsupportedTypes = true;
    });
});

Polymorphic Serialization

// Configure type registry for polymorphic serialization
services.AddUniversalSerializer(builder => {
    // Enable type discriminator
    builder.ConfigureOptions(options => {
        options.EnableTypeDiscriminator = true;
        options.TypeDiscriminatorPropertyName = "$type";
    });
    
    // Register types
    builder.ConfigureTypeRegistry(registry => {
        registry.RegisterType<Dog>("dog");
        registry.RegisterType<Cat>("cat");
        
        // Or automatically register all subtypes of Animal
        registry.RegisterSubtypes<Animal>();
    });
});

// Define types
public abstract class Animal
{
    public string Name { get; set; }
}

public class Dog : Animal
{
    public string Breed { get; set; }
}

public class Cat : Animal
{
    public int Lives { get; set; }
}

// Use polymorphic serialization
var animals = new List<Animal>
{
    new Dog { Name = "Rex", Breed = "German Shepherd" },
    new Cat { Name = "Whiskers", Lives = 9 }
};

var serializer = _serializerFactory.GetJsonSerializer();
string json = serializer.Serialize(animals);
// Results in type-aware JSON with $type property
// Deserialize back to correct types
var deserializedAnimals = serializer.Deserialize<List<Animal>>(json);

Binary Serialization

// Configure and use binary serializers
services.AddUniversalSerializer(builder => {
    builder.AddMessagePackSerializer();
});

// In your code
var messagePackSerializer = _serializerFactory.GetMessagePackSerializer();
byte[] binary = messagePackSerializer.SerializeToBytes(data);
var result = messagePackSerializer.DeserializeFromBytes<MyData>(binary);

Supported Formats

Format Content Type File Extension Package Dependency
JSON application/json .json System.Text.Json (built-in)
XML application/xml .xml System.Xml.Serialization (built-in)
YAML application/yaml .yaml YamlDotNet
TOML application/toml .toml Tomlyn
MessagePack application/x-msgpack .msgpack MessagePack

License

This project is licensed under the MIT License - see the LICENSE file for details.

Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.3 134 6/18/2025
1.0.2 128 6/18/2025
1.0.1 124 6/18/2025
1.0.0 220 6/13/2025

## v1.0.0 (major)

- Refactor project files to use custom SDKs for improved build management. Updated UniversalSerializer, UniversalSerializer.Benchmarks, and UniversalSerializer.Test projects to utilize ktsu.Sdk.Lib, ktsu.Sdk.ConsoleApp, and ktsu.Sdk.Test respectively. This change enhances compatibility and streamlines the build process across different project types. ([@matt-edmondson](https://github.com/matt-edmondson))
- Refine StringConvertibleTypeConverter and enhance documentation ([@matt-edmondson](https://github.com/matt-edmondson))
- Add compression and encryption support to serializers, including the implementation of ICompressionProvider and associated compression algorithms (GZip, Deflate). Integrated compression functionality into SerializerBase for byte serialization. Established security infrastructure with IEncryptionProvider and EncryptionType enum. Enhanced YAML polymorphic type converter and improved overall build stability by addressing compilation errors and validation issues. ([@matt-edmondson](https://github.com/matt-edmondson))
- Refactor SerializerServiceCollectionExtensions and update serializer registrations ([@matt-edmondson](https://github.com/matt-edmondson))
- Enhance serializer functionality and update dependencies ([@matt-edmondson](https://github.com/matt-edmondson))
- Add enum serialization format options to serializer settings ([@matt-edmondson](https://github.com/matt-edmondson))
- Add support for custom type conversion in serializers ([@matt-edmondson](https://github.com/matt-edmondson))
- Add support for MessagePack, Protobuf, and FlatBuffers serialization ([@matt-edmondson](https://github.com/matt-edmondson))
- Add YAML serialization support ([@matt-edmondson](https://github.com/matt-edmondson))
- Add initial project files for UniversalSerializer, including configuration for package management and serialization rules. Implemented core serializer interfaces and added YAML, JSON, and XML serializers with dependency injection support. Updated README for documentation and added initial tests for serializer functionality. ([@matt-edmondson](https://github.com/matt-edmondson))
- Add community and core plugins configuration; update project dependencies ([@matt-edmondson](https://github.com/matt-edmondson))
- Add support for MessagePack, Protobuf, and FlatBuffers serializers ([@matt-edmondson](https://github.com/matt-edmondson))
- Add core serialization framework with JSON and XML support ([@matt-edmondson](https://github.com/matt-edmondson))
- Enhance serializer options with format-specific keys and advanced customization ([@matt-edmondson](https://github.com/matt-edmondson))
- initial commit ([@matt-edmondson](https://github.com/matt-edmondson))
- Update .editorconfig to disable var usage for built-in types, modify .runsettings for parallel test execution, enhance .gitignore for SpecStory files, and update Directory.Packages.props with new dependencies and versioning. Introduce global.json for SDK management and refine PSBuild.psm1 for improved package publishing and version handling. ([@matt-edmondson](https://github.com/matt-edmondson))
- Update dependencies and enhance serialization options ([@matt-edmondson](https://github.com/matt-edmondson))
- Remove PowerShell script for adding missing using statements and update README to reflect package name change to ktsu.UniversalSerializer. Add a new rule for ensuring unit and integration tests with > 80% code coverage. ([@matt-edmondson](https://github.com/matt-edmondson))
- Remove unnescessary file ([@matt-edmondson](https://github.com/matt-edmondson))
- Complete implementation tasks for UniversalSerializer project ([@matt-edmondson](https://github.com/matt-edmondson))
- Add TOML serialization support ([@matt-edmondson](https://github.com/matt-edmondson))
- Add .cursorignore for SpecStory backup files, update Directory.Packages.props with main and test dependencies, and refactor project files to use Microsoft.NET.Sdk. Added new history file for library development progress and updated .gitignore to include backup files. ([@matt-edmondson](https://github.com/matt-edmondson))
- Update task list to mark build pipeline configuration as complete ([@matt-edmondson](https://github.com/matt-edmondson))
- Add INI serialization support ([@matt-edmondson](https://github.com/matt-edmondson))
- Add common and type registry option keys for serialization ([@matt-edmondson](https://github.com/matt-edmondson))
- Add streaming and compression support to serializers, including new methods in ISerializer for stream handling. Introduced CompressionType enum and updated SerializerOptions for compression settings. Enhanced TOML serializer with complete object conversion and added parameter validation for compliance. Fixed various compilation errors and improved YAML polymorphic type converter implementation. ([@matt-edmondson](https://github.com/matt-edmondson))
- Refactor SerializerRegistry and TomlSerializer for improved clarity and performance ([@matt-edmondson](https://github.com/matt-edmondson))
- Refactor serializer interfaces and implementations to improve code clarity and consistency. Removed unnecessary using directives, added access modifiers to interface members, and standardized variable declarations. Enhanced type handling in various serializers and converters, ensuring better adherence to coding standards and practices. ([@matt-edmondson](https://github.com/matt-edmondson))
- Remove Protobuf and FlatBuffers support from UniversalSerializer ([@matt-edmondson](https://github.com/matt-edmondson))
- Add polymorphic serialization support for JSON, XML, and YAML ([@matt-edmondson](https://github.com/matt-edmondson))
- Refactor SerializerRegistry and update serializer methods ([@matt-edmondson](https://github.com/matt-edmondson))
- Add XML serializer options, enhance JsonPolymorphicConverter for better type handling, and fix missing using statements across various serializers. Implemented HasPolymorphicTypes method in TypeRegistry and updated SerializerOptionKeys for XML settings. Addressed pattern matching issues in TOML and YAML serializers. ([@matt-edmondson](https://github.com/matt-edmondson))
- Update README.md with comprehensive documentation for UniversalSerializer ([@matt-edmondson](https://github.com/matt-edmondson))
- Add LZ4 compression support and enhance serializer error handling ([@matt-edmondson](https://github.com/matt-edmondson))
- Add implementation tasks for UniversalSerializer ([@matt-edmondson](https://github.com/matt-edmondson))
- Enhance serializer functionality and update project files ([@matt-edmondson](https://github.com/matt-edmondson))
- Add polymorphic serialization support with type discriminator options ([@matt-edmondson](https://github.com/matt-edmondson))
- Refactor SerializerRegistry and update serialization methods ([@matt-edmondson](https://github.com/matt-edmondson))
- Remove INI serialization support ([@matt-edmondson](https://github.com/matt-edmondson))