Skip to content

Latest commit

 

History

History
96 lines (65 loc) · 2.4 KB

File metadata and controls

96 lines (65 loc) · 2.4 KB

Shuttle.Core.Serialization

The Shuttle.Core.Serialization package provides a consistent interface for serializing and deserializing objects.

Installation

dotnet add package Shuttle.Core.Serialization

ISerializer interface

The core of the library is the ISerializer interface:

public interface ISerializer
{
    string Name { get; }
    Task<object> DeserializeAsync(Type type, Stream stream, CancellationToken cancellationToken = default);
    Task<Stream> SerializeAsync(object instance, CancellationToken cancellationToken = default);
}

The following implementation is provided:

  • JsonSerializer: uses System.Text.Json for serialization.
  • SerializerService: used to manage multiple ISerializer instances.

Usage

AddJsonSerializer

To register the JsonSerializer, use the AddJsonSerializer extension method on IServiceCollection:

services.AddJsonSerializer(options => 
{
    options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
});

The options is of type JsonSerializerOptions.

ISerializerService

The ISerializerService can be used to manage multiple serializers:

public interface ISerializerService
{
    IEnumerable<ISerializer> Serializers { get; }
    ISerializerService Add(ISerializer serializer);
    bool Contains(string name);
    ISerializer Get(string name);
}

You can use the SerializerService implementation to store and retrieve serializers by their Name:

var serializerService = new SerializerService();

serializerService.Add(new JsonSerializer(Options.Create(new JsonSerializerOptions())));

if (serializerService.Contains("Json"))
{
    var serializer = serializerService.Get("Json");
}

Methods

SerializeAsync

Task<Stream> SerializeAsync(object instance, CancellationToken cancellationToken = default);

Returns the object as a Stream.

DeserializeAsync

Task<object> DeserializeAsync(Type type, Stream stream, CancellationToken cancellationToken = default);

Deserializes the Stream into an object of the given Type.

DeserializeAsync<T> (Extension method)

Task<T> DeserializeAsync<T>(Stream stream, CancellationToken cancellationToken = default);

Deserializes the Stream into an object of the given type T.